Instantiating as GameObject

Please, someone would be so kind to explain what exactly is the difference between instantiating like this:

Instantiate(hero, new Vector3(mousePosX, mousePosY, 0), quaternion.identity);

and this:

GameObject newHero = Instantiate(hero, new Vector3(mousePosX, mousePosY, 0), quaternion.identity) as GameObject;

I tried both ways and can’t see anything different in the Hierarchy, or anywhere else.

Any light about the topic is greatly appreciated!
thanks!

1 Like

Hi Martin,

The Instantiate method returns an object of type Object, not of type GameObject. In past versions of Unity, you had to explicitely cast the returned object. Otherwise, the compiler would have thrown an error. As it seems, this behaviour was changed in one of the newer versions of Unity, maybe in 5 or 2017. I assume the returned object gets casted implicitely now.

Game developers who have been using Unity for a couple of years still cast the object explicitely. Maybe out of habit, maybe because they regard it as good practice.


See also:

4 Likes

Nina, thanks so much, this makes sense. And thanks so much for the prompt response.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms