Unity3d script losing AudioClip reference when using AddComponent()

十年热恋 提交于 2019-12-24 00:37:30

问题


I have script (#2) below with a public AudioClip variable. When I 'addComponent', it loses that reference.

I've tested manually adding it to an object in the editor, and in that case it works OK. Why does my script added during runtime lose the reference?

GameObject 1: has this script (#1) attached

void HitByRay() {
    clock = GameObject.FindGameObjectWithTag("Clock_Arrow").GetComponent<Clock>();
    clock.gameObject.AddComponent<Tick_Audio_Script>();
}

Which attaches the following script (#2) to the 'Clock' object.

public int safetyCounter;
float gapToNext;
public AudioClip tickAudio;

// Use this for initialization
void Start () {
    startTicker(100);
}

void startTicker(int maxTicks)
{
    safetyCounter = maxTicks;
    gapToNext = 1f;
    playTick();

}

void playTick()
{
    Debug.Log("Tick");
    if (gapToNext < 0.1 || safetyCounter == 0)
    {
        Debug.Log("We're done...!");
        return;
    }
// **ERROR HERE CLIP NOT FOUND** 
    AudioSource.PlayClipAtPoint(tickAudio, gameObject.transform.position, 1f);

    gapToNext = gapToNext * 0.97f;
    safetyCounter--;
    Invoke("playTick",gapToNext);
}

Here's the script in the editor, where I've assigned the audioclip.

But when it's attached via 'AddComponent', the reference to that clip does not come through (after I hit play and 'hit' my trigger object which attaches this script)? This results in a null reference error as there is no clip found to be played.

My AudioListener (located on a different object) is working, as there are other sounds being played correctly in the scene.

Again, I've tested adding this script manually to any object pre-run in the editor it works. Why is this?


回答1:


This has a simple solution. You can do one of the following:

1) Create a prefab and add it to "clock" with the needed references.

2) do this:

void HitByRay() {
    clock = GameObject.FindGameObjectWithTag("Clock_Arrow").GetComponent<Clock>();
    clock.gameObject.AddComponent<Tick_Audio_Script>();
//NEW PART
    clock.gameObject.GetComponent<Tick_Audio_Script>().TickAudio = (desired Audio);
}

Hope this helps.



来源:https://stackoverflow.com/questions/37968839/unity3d-script-losing-audioclip-reference-when-using-addcomponent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!