Search code examples
c#unity-game-enginecasting

Difference between casting and GetComponent in Unity


I’ve looked for information on this but I still have lots of doubts. Imagine we instantiate an object with a “Movement” component in it. What is the difference between this three:

Movement movement = Instantiate(anObject).gameObject.GetComponent<Movement>();

Movement movement = Instantiate(anObject) as Movement;

Movement movement = (Movement)Instantiate(anObject);

Solution

  • There isn't anything special about the type return by Instantiate, it's just a normal Unity Object clone of whatever object you put in. If you put in a GameObject, you'll get a GameObject out. If you put in a Transform, you'll get a Transform out (with its parent gameObject also cloned).

    This means if your anObject instance is a GameObject type, casting it to Movement won't work. You'd have to use GetComponent<Movement>()

    Cases 2 and 3 only differ based on the use of As vs casting. The difference between the two operations has been answered before.