FindObjectOfType VS GetComponent

Hi,

When attempting to call the GameSession’s ProcessPlayerDeath() method from the Player.cs, I first tried calling it by typing the following statement:

GetComponent().ProcessPlayerDeath();

However, this didn’t have the desired effect (i.e. the scene didn’t restart upon my avatar falling into the spikes).

I then did as instructed in the video and changed the statement to read:

FindObjectOfType().ProcessPlayerDeath();

…and it worked!

Is the reason because the Player.cs can only get components from the player object itself and not components from other objects?

Also, I realise that I thought GetComponent<> and FindObjectOfType<> did very similar jobs and so could work interchangeably, but I think I must be mistaken in this regard…

Any further support you can offer re: the different between these two methods would be gratefully received.

Thanks.

Hi man!

The GetComponent<> method and the FindObjectOfType<> are very similar as you said, but there is a main difference.

The first one Get a specified Component only into the gameobject in which the script is inserted. For instance if you put the Player script into the Player gameobject and try to get a component that is into another gamobject it will not find it.

The second one try to Find a specified Object into the whole scene and once the object is found, then you can access all its public methods and attributes.

So, you can also access a particualar component into another gameobject.

Just for fun try to access the Rigidbody2D velocity of the player by the GameSession script.

You will find that you need to do something like:

Debug.Log(FindObjectOfType<Player>().GetComponent<Rigidbody2D>().velocity);

Privacy & Terms