Home > Blockchain >  Difference between casting and GetComponent in Unity
Difference between casting and GetComponent in Unity

Time:08-24

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);

CodePudding user response:

The first line is the correct way of getting a component. By the way, you can call GetComponent directly on Instantiate, because it returns a GameObject like this:

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

Your second and third option does not work, because you can't just convert a new GameObject to a component.

CodePudding user response:

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.

  • Related