I am trying to instantiate a GameObject and keep a reference to it but for some reason the above error appears every time it is instantiated even though the instantiation still goes through. The line of code it points me to is this: GameObject next = Instantiate(prefab);
Like I said, the instantiation still works correctly, but in the interest of stability, I would like to get rid of this error. What does Unity want from me?
3 Answers
You're all wrong. Roughly speaking, Instantiate returns
WHAT YOU PASS IN.
if you have this ...
public GameObject modelDinosaur;
you can indeed have this
GameObject nu = Instantiate(modelDinosaur);
No need to cast. (It's totally OK to cast if you want to.)
Yes, for a prefab, do exactly what everyone tells you above
GameObject nu = (GameObject)Instantiate(yourPrefab);
BTW it is idiomatic to use "nu" (like "new") as the temporary variable. ("new" is a keyword of course, you can't use that.)
Most commonly you then do these things ..
GameObject nu = Instantiate(modelDinosaur);
YourDinoScript nuD = nu.GetComponent<YourDinoScript>();
yourDinoList.Add(nuD);
nu.name = "dynamic " + counter;
nuT = nu.transform;
nuT = blah blah
nuT = your holder
nuT = logic position
etc etc
PS: regarding Unity's doco, you might as well read the ravings of a drunk chatbot. Forget it.
The Unity Instantiate
method has a return type of Object
. You need to instantiate your prefab as a GameObject
if you want to store it in a GameObject
variable.
Assuming you are using C#, you can instantiate a GameObject and store it in a variable like so:
GameObject myGameObject = Instantiate(prefab) as GameObject;
Instantiate()
return an Object
, You need to cast it to GameObject
Explicitly.
Try this:
GameObject next = (GameObject)Instantiate(prefab);
More information:
Instantiate()
signature: public static Object Instantiate(Object original)
This clearly shows that the return type is Object
and not Gameobject
Reference
Please refer to this for more details