1

I have 4 instances of 'GameObjectONE' in my scene. The script that is attached to GameObjectONE invokes a delegate. I have another object called GameObjectTwo in my scene. The script that is attached to GameObjectTwo contains a function that subscribes to the delegate invoked by GameObjectONE. However, that function gets called 4 times. I guess that's because there are 4 copies of GameObjectONE in the scene. Is there anyway to have the function inside of GameObjectTwo get called only once, regardless of how many instances of GameObjectONE exist in the scene?

This is pseudo code, but it shows what I'm trying to achieve

using System;
using UnityEngine;

public class GameObjectONE : MonoBehaviour
{
public static event Action<Vector3> OnClick;

private void Update()
{
    if (currentlySelected)
        if (clickedOnTerrain)
        {
            var clickPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            OnClick?.Invoke(clickPos);
            MoveToTarget();
        }
}

}

Second class

using UnityEngine;

public class GameObjectTWO : MonoBehaviour
{

private void Awake()
{
    GameObjectONE.OnClick += AssignTargets;
}

private void OnDestroy()
{
    GameObjectONE.OnClick -= AssignTargets;
}


private void AssignTargets(Vector3 clickPos)
{
    //Based on the click position, find and assign a target for each unit.
}
}
Sean Carey
  • 799
  • 5
  • 12
  • I'd say the condition to call the event on GameObjectONE is met on all four objects so they all call the static event. – Everts Dec 29 '18 at 15:50

1 Answers1

0
  1. Make the event in GameObjectONE static (so it class not object related).
  2. In GameObjectTWO subscribe to this event by calling a class method (not object)

    GameObjectONE.OnEventThatIsFiredByGameObjectOne += ...

rootpanthera
  • 2,731
  • 10
  • 33
  • 65
  • That’s already the case. The event is already static and I already subscribe to it by calling a class method. – Sean Carey Dec 29 '18 at 12:49