Question about the Defender type

When we change from GameObject type to Defender type

private void SpawnDefender(Vector2 roundedPos)
{
Defender newDefender = Instantiate(defender, roundedPos, Quaternion.identity) as Defender;
}

  1. Why we do it?
    2)How can we instantiate it if its not a gameobject anymore?

i got bit confused here.

Hi Shaktillar,

The Instantiate method instantiates our game object, no matter what we do else in our script. With as Defender, we cast the returned object, so we can assign it to the Defender variable. This way, we can directly access the Defender object in the next line and don’t have to call GetComponent on the GameObject object.

Did this clear it up for you?


See also:

Yes i got this part what i dont get is this

public class DefendersSpawner : MonoBehaviour
{
Defender defender;

This was a GameObject but now we changed to a class type.

If we are interested in the Defender component only and if we want to be able to access it multiple times, it makes sense to assign the reference (“link”) to it to a variable of type Denfender. If we used GameObject, we would have to call GetComponent each time we want to do something with the Defender component. That would be a waste of resources.

public class Defender : MonoBehaviour
{
[SerializeField] int starCost = 100;
}
Yeah but i see only this in the Defender script and at the moment we dont use nothing from here.Maybe later in the course.Thats what makes the confusion to me we refer to Defender type script but we dont use it.

I see. In this case, your confusion makes sense. The Defender class is not complete yet. If you are curious, you could take a look at the final class here.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms