- Home /
Is it necessary to assign the result of Instantiate() to a variable and is there a need to always typecast?
If you're already using a variable pre-typed to GameObject which stores the prefab via the inspector, is it proper to just call Instantiate statically using that public inspector var as an argument? It stores the prefab and does instantiate, but I'm a bit confused by how Unity C# expects to work with the instance at this point because I saw another example where a post-type as casting was used...
eg, C#
public GameObject somePrefab; // drag prefab into exposed inspector field
void Start()
{
Instantiate(somePrefab, startPosition, startRotation);
}
versus say:
somePrefab = Instantiate(somePrefab, startPosition, startRotation) as GameObject;
or
somePrefab = Instantiate(GameObject)Instantiate(somePreb, startPosition, startRotation);
I guess it's a bit confusing that the public var above is already typed to GameObject, stores the prefab via the inspector and yet Instantiate returns type of Object not GameObject? I've combed through the q/a but would love some simplified summary of this issue. Thanks to any who may shed some light.
Well looks like I figured this out, I think. It takes one public variable to store the prefab from the editor and another variable to store the instance resulting from the Instantiate() call. I get it. What threw me off was that Instantiate() was returning an Object type, not a GameObject and so none of my GameObject dependent code was able to use my instance until I recast it as a GameObject. I had to the solution but was too dull to realize it!
Answer by rutter · Mar 09, 2012 at 11:15 PM
Instantiate()
returns a reference to the created object in case you need to do anything further with it. If you don't, there's no need to store the value.
If whatever you instantiated is a GameObject
, it should always be safe to cast the return as one.
The reasoning for this is fairly complicated and tricky to explain in a nutshell, but if you're curious: it has to do with something called polymorphism. Instantiate()
takes and returns an Object
reference because it can be called to create objects from many different classes, all of which inherit from UnityEngine.Object
. This makes the function very powerful, but is a little bit confusing if you don't know about it.