虽然它仍在移动,但我可能会再次将鼠标悬停在它上面,在这种情况下我想要
它重新启动,因此它停止影响完全相同的功能
按钮并重新启动另一个。我只是不知道如何识别
同一函数的哪个调用会影响我给定的组件。或者我应该
将此脚本添加到每个对象,以便它只影响那个对象?
一种解决方案是将包含协程函数的脚本附加到每个游戏对象。如果您不想这样做,那么还有另一种方法可以做到这一点。
首先,仅仅存储IEnumerator 是不够的。您需要一种方法来识别在最后一个协程中运行的 GameObject。
1.获取一个可用于标识对象的值。在这种情况下,GetInstanceID() 的实例 ID 应该没问题。
2. 制作一个简单的struct 来保存旧的协程信息。
3。最后,制作一个字典,其中包含实例 ID(key) 和 #2 中的结构体作为值。
有了这三样东西,就可以启动一个协程,添加到Dictionary。协程完成后,从Dictionary 中删除instance ID。
下面的代码将使一个协程控制多个对象,而无需将协程函数放在它自己的脚本中。最大的区别在于,当在同一函数上调用新的协程时,它仅停止该对象上的旧协程,然后创建一个新协程并启动它。
这是我使用的。它的注释很好,以便您知道发生了什么。
Dictionary<int, MoveInfo> movingObject = new Dictionary<int, MoveInfo>();
public void Move(Transform from, Transform to, float overTime)
{
MoveInfo moveInfo;
//Check if the Object exist in the Dictionay
if (movingObject.TryGetValue(from.GetInstanceID(), out moveInfo))
{
//This Object exist and therefore, the coroutine function is already running. Stop it
//Remove it from the Dictionary
movingObject.Remove(from.GetInstanceID());
//Stop the old coroutine
StopCoroutine(moveInfo.currentCoroutine);
}
//Create a new coroutine
moveInfo = createMoveInfoInstance(from);
//Add it to the dictionary
movingObject.Add(from.GetInstanceID(), moveInfo);
//Get instance of the new coroutine we are about to start
moveInfo.currentCoroutine = _Move(moveInfo, from, to, overTime);
//Modify the dictionary because the Add function does not update the currentCoroutine reference
movingObject[from.GetInstanceID()] = moveInfo;
//Start the coroutine
StartCoroutine(moveInfo.currentCoroutine);
}
MoveInfo createMoveInfoInstance(Transform from)
{
MoveInfo moveInfo = new MoveInfo();
moveInfo.instanceID = from.GetInstanceID();
return moveInfo;
}
IEnumerator _Move(MoveInfo moveInfo, Transform from, Transform to, float overTime)
{
Vector2 original = from.position;
float timer = 0.0f;
Debug.Log("New Coroutine Started");
while (timer < overTime)
{
float step = Vector2.Distance(original, to.position) * (Time.deltaTime / overTime);
from.position = Vector2.MoveTowards(from.position, to.position, step);
timer += Time.deltaTime;
yield return null;
}
//Remove it from the Dictionary if it exist
if (movingObject.ContainsKey(from.GetInstanceID()))
{
movingObject.Remove(from.GetInstanceID());
}
}
public struct MoveInfo
{
public IEnumerator currentCoroutine;
public int instanceID;
public MoveInfo(IEnumerator currentCoroutine, int instanceID)
{
this.currentCoroutine = currentCoroutine;
this.instanceID = instanceID;
}
}