0

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);
Marc
  • 5
  • 1
  • Getting a component is far different than casting. GetComponent finds a specific Component attached to the object in question. I suggest reading about [cast and type conversions](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/casting-and-type-conversions) – hijinxbassist Aug 23 '22 at 19:25

2 Answers2

0

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.

Marten
  • 68
  • 2
  • 5
  • I understand! Thank you! What will the use be for casting with “(Movement)” and “as Movement” be? – Marc Aug 23 '22 at 20:02
  • This casting can be used for example, to convert a base class into a subclass. Let's say you have the base class car and two sub classes like Sedan and SUV. If you have the base class instance, you can convert them into the subclass like this: (SUV)car. This explanation is of course dumbed-down, casting is much easier to understand if you understand the concept of object-oriented programming. – Marten Aug 23 '22 at 21:30
0

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.

ipodtouch0218
  • 674
  • 1
  • 2
  • 13
  • Hi! First of all thank you for your answer. Then, what is the use for casting with () and “as”? – Marc Aug 23 '22 at 20:02
  • @Marc the "As" vs "()" casting methods are answered [in the link I sent in the answer](https://stackoverflow.com/questions/955250/c-sharp-difference-between-casting-and-as). An "as" cast failing will return null, while a "()" cast failing will throw an exception – ipodtouch0218 Aug 24 '22 at 15:30