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! :)
Answer by Hellium · Apr 26, 2020 at 09:36 AM
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()
{
Died?.Invoke();
}
// 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;
opponentEconomyScript.AddMoney(unit.DeathGold);
};
unit.Died += onUnitDeath;
}
Your answer
Follow this Question
Related Questions
LensFlare component is missing Directional property in Script, does only appear in editor? 0 Answers
Trigger enabling component works in one statement but not another? 1 Answer
accessing a script using a variable with getComponent, then accessing a variable inside that script 1 Answer
My collectable objects don't respond like they should after calling a coroutine for the first time? 0 Answers
How do I make my player object shoot shots on mobile? 0 Answers