简体   繁体   中英

Subscribing to a delegate that is invoked multiple times

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.
}
}
  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 += ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM