简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM