- Home /
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'.
Answer by Reclusiarch · Dec 08, 2013 at 05:55 AM
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;
}
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Unity v4.1.5 Crashes When Using Resources.Load 0 Answers
Texturing a mesh created at runtime 1 Answer