- Home /
Instantiating a prefab through C# script
I am making a background music script that checks if a specific prefab is in a scene. If the prefab does not exist, instantiate that prefab which the audio source is attached to. All my code works besides actually instantiating the prefab. Here is my code
private GameObject music;
void Start () {
music = GameObject.Find("GameMusic");
Debug.Log("Started");
Debug.Log (music);
if (music == null) {
Debug.Log("GameObject GameMusic found");
Instantiate(music);
}
}
I keep getting an error saying "ArgumentException: The thing you want to instantiate is null." Any ideas?
private GameObject music;
void Start () {
music = GameObject.Find("Game$$anonymous$$usic");
Debug.Log("Started");
Debug.Log (music);
if (music == null) {
Debug.Log("GameObject Game$$anonymous$$usic found");
Instantiate(music);
}
}
Wait... your if statement reads like:
if the GameObject variable called music is null, then invoke this debug.log static method followed by instantiate an object that i just confirmed was null.
So, music was null, you tried to instantiate a null object, that doesn't work and the output was what it should be. $$anonymous$$usic should NOT be null and then instantiate
if (music != null) {
// blah blah
}
Then how do I insert the prefab without it being in there first. I read on the scripting API that instantiate was a cloning method but it noted that the gameobject didnt have to previously exist. If your telling me I am using the wrong method or I need a better way around this, please tell me what I can do to fix it and not just tell me I'm wrong.
Seeing that music is a private variable means that you don't assign it in the inspector.
Here's the skinny. Quick and dirty.
Public variable of type GameObject.
public GameObject music;
You can keep the stuff in the start, but you need to assign this script to an object(camera, empty gameobject, whatever). Then you will be able to drag from the assets to the property now called $$anonymous$$usic on the object in the inspector a GameObject. This will link the two together. Now when Start is called music will not be null on the Game Object the script resides.
If it's actually not a GameObject and really an AudioClip, then change the type to match the asset requirement.