FindObjectOfType vs GetComponent

Hello i am fairly new to programming and i wanted to ask why in Enemy script we use FindObjectOfType() but in EnemyMover and EnemyHealth scripts we use GetComponent() and not FindObjectOfType()?

Hi,

GetComponent works only if we have the reference to the game object to which the component is attached. For example, if we have a player game object with a Player component and a Health component, we could find the Health object in the Player object with GetComponent.

FindObjectOfType searches the entire scene and returns the first object it finds, whatever Unity defines as “first”. If you have multiple enemies and call FindObjectOfType multiple times to find Enemy objects, you would very likely get the same Enemy object each time.

Did this answer your question? :slight_smile:


See also:

Thank you for the quick reply.

I have 2 more questions:

  1. Could we use GetCompoment() instead of FindObjectOfType() or that would not work?

  2. The way the FindObjectOfType works wouldn’t be very resource heavy with searching the whole scene?

  1. The Bank is a unique component in our scene. There is only one. For this reason, it is fine to look for it via FindObjectOfType. Furthermore, we cannot assign the reference to the Bank object manually to the enemy because “the enemy” does not exist while we are developing our game. It gets created during runtime, thus it needs to find objects itself via code.

  2. You are right. FindObjectOfType is indeed resource-intensive. However, in our little game, we will not notice any difference if we opted for another solution. Theoretically, we could have dropped the Unity side of the bank and made it a pure C# script with a singleton implementation. Sounds cryptic? Well, that’s the reason why Gary stuck with what had already been taught instead of introducing new concepts. If you are familiar with C#, feel free to replace Gary’s Bank with your own solution.

I see thank you so much for answering my questions.
Have a nice day.

You’re welcome. Have a nice day! :slight_smile:

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

Privacy & Terms