How can I reference a script in a specific gameobject if that same script exists in other gameobjects?

Basically title. I have two “Nexus” game objects, one for red player, one for blue player.
Each nexus has an economy script (the same script) attached to them.

When a blue unit dies, I want it to run an AddMoney() method in the RED Nexus. When a red unit dies, i want it to run an AddMoney() method in the BLUE nexus.


I’ve tried all i can think of with FindObjectofType, GetComponent, etc. Ideally, I just want it to search for all moneyhandler scripts in the game at the start, check what the tag is of their gameobjects (each nexus), and based on that assign them as either redMoneyHandler or blueMoneyHandler. Then, when the unit dies, I can say redMoneyHandler.AddMoney(deathGold); and be done with it.

I’m not exactly sure how I’d do that though.

Thanks in advance! :slight_smile:

There are several ways to do it, and in your case, making the units look for the nexus is not a good idea.

Your units should not even reference the nexus at all. They should just die, nothing more. Then, another entity would score when a unit dies.

// Unit.cs

[SerializeField] private int deathGold;

public event Action Died;

public int DeathGold { get { return deathGold; } }

public void Kill()

// Spawner.cs

// Drag & drop the nexus in the inspector
[SerializeField] private OpponentEconomyScript opponentEconomyScript;

private void SpawnUnit()
    Unit unit = Instantiate(unitPrefab);
    System.Action<Unit> onUnitDeath = null;
    onUnitDeath = () =>
         Debug.Log("Unit died");
         unit.Died -= onUnitDeath;
    unit.Died += onUnitDeath;