Hi Fernando,
To some degree the cast doesn’t make a lot of difference, in this specific scenario, for example, in the case of the defender you could cast it as a Defender because the object you were instantiating has a Defender script attached to it, you knew the/a type in advance. So you get an object of type Defender, but if you then wanted to access its GameObject you could use defender.gameObject
for example.
In the case of the Projectile you could have done the same, e.g. cast it as a Projectile, as you know there is a Projectile script attached, and then if you needed to access the transform for example you could have used projectile.gameObject.transform
.
If you cast as a GameObject then you don’t have access directly to the specific component, but you can access any of the components by using GetComponent<>
, so in the case of the defender you could use object.GetComponent<Defender>()
or, in the case of the projectile you could have used object.GetComponent<Projectile>()
- in both cases object being the variable you declared to store the reference to the instantiated object.
The approach you use will often depend one what you want to do, for example, if you needed access to just the transform, casting as a GameObject will then require a little less code. If you just needed to access properties of the Projectile, then casting as a Projectile will then require a little less code.
Cast the object to the type that you need, or need most.
Hope this helps.