- Home /
How can I instantiate an object without using Unity?
So I've gotten the "the thing you want to instantiate is null error" one too many times and I'm stuck. I already know that if I go into the Unity GUI and go and drag the right object type into the public variable i create, voila it works....
What I don't know is why?? Why can't I just make it a private variable and instantiate the object using code? There has to be a way to do this, but I can't figure it out.
Why doesn't this work without the whole drag and drop routine....BUT it does work if i drag a WackAMole onto the public WackAMole object in my Annoying script.....
public class WackAMole : MonoBehaviour {
public string FMe = "go jump off a bridge"
}
public class Annoying: MonoBehaviour {
public WackAMole wacky;
private void Start () {
wacky = (WackAMole)Instantiate(wacky);
}
}
Answer by gRntaus · Apr 11, 2013 at 05:12 AM
You could try the following if you wanted (I'm writing in c# you'd have to look up the js equivalent if you're working with that).
private myGameObject = Resources.Load("myObjectName") as GameObject;
For this to work in your game hierarchy you'd need to make a folder called Resources and move the GameObject into that folder and it should work.
The reason just creating a GameObject variable doesn't work is that you aren't referencing it in any way.