我的场景中有4个“ GameObjectONE”实例。附加到GameObjectONE的脚本调用一个委托。我的场景中还有另一个名为GameObjectTwo的对象。附加到GameObjectTwo的脚本包含一个订阅由GameObjectONE调用的委托的函数。但是,该函数被调用了4次。我猜那是因为场景中有4个GameObjectONE副本。无论如何,无论场景中存在多少GameObjectONE实例,GameObjectTwo内部的函数仅被调用一次?
这是伪代码,但它显示了我要实现的目标
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();
}
}
}
第二堂课
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.
}
}
答案 0 :(得分:0)
在GameObjectTWO中,通过调用类方法(不是对象)来订阅此事件
GameObjectONE.OnEventThatIsFiredByGameObjectOne + = ...