问题
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