Problem adding component to object at runtime

At the end of a long procedural generation cycle, my Unity project tries to do the following:

if(GameObject.Find("Main Camera") != null){
			GameObject cam = (GameObject) GameObject.Find("Main Camera");
			AudioSource audioSource = cam.AddComponent<AudioSource>();
			audioSource.clip = Resources.Load("music/music") as AudioClip;
			audioSource.Play();
			//s.clip = a;
		}

This code executes just fine, and if you print out ‘cam’ or ‘audioSource’ they are non-null. However, this code does not add any such component to the camera object. The music file loads and is also non-null.

Here’s the weird thing. If you wait until the procedural generation is finished, load the above code into a button on the editor and press it, then the component is added fine and everything is normal. What’s going on? Why won’t this work normally during the generation phase?

I realise this question is a little vague. If can give any extra info let me know.

FYI, you always have a reference to the main camera via 'Camea.main'.

1 Answer

1

try this

        if (GameObject.Find("Main Camera") != null)
        {
            GameObject cam = (GameObject)GameObject.Find("Main Camera");
            cam.AddComponent<AudioSource>();
            AudioSource audioSource = (AudioSource)cam.gameObject.GetComponent(typeof(AudioSource));
            audioSource.clip = Resources.Load("music/music") as AudioClip;
            audioSource.Play();
            //s.clip = a;
        }