Alternative to FindObjectOfType<Bank>();

As an alternative to this method, can/should I create a [SerializeField] Bank bank; in the Enemy script and drag and drop the GameObject Bank into the slot? (not sure what you call that method) I understand that in this case FindObjectOfType is not so taxing as we only have one GameObject called Bank. My question is more general, what would the optimal practice be here and in general to communicate between two scripts/GameObjects?

1 Like

Yes, it is better to have a direct reference than to try and find it first.

However - as in this case - that is not always possible. Prefabs cannot have a reference to something in the hierarchy. Only when the prefab is instantiated into the scene does it become part of the hierarchy, and only then can it have a reference to something else in the hierarchy. In those cases you need to either use FindObjectOfType to find what you need - like we did here - or the object that instantiated the prefab instance can assign the reference.

2 Likes

How would you do that?

The script that requires the reference would have a setter method or, if there are several such fields, a Setup method that takes all the references

public void Setup(Bank bank)
{
    this.bank = bank;
}

Then, once you’ve instantiated the prefab, you get the script and call the method. This assumes that the spawner has a reference to Bank (in this case)

GameObject enemyInstance = Instantiate(enemyPrefab, transform);
if (enemyInstance.TryGetComponent<Enemy>(out Enemy enemy))
{
    enemy.Setup(bank);
}
1 Like

thank you very much!

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

Privacy & Terms