gpt4 book ai didi

c# - 将不同的功能收集到一个委托(delegate)

转载 作者:太空宇宙 更新时间:2023-11-03 23:03:51 25 4
gpt4 key购买 nike

我有不同的函数 我想被彼此调用。都是UI动画,一种是旋转,一种是缩放,一种是移动等等。我希望链接它们,所以在 coroutine 结束时,如果订阅了其他内容,则会触发一个事件。目前,我必须为所有 创建委托(delegate),这会使代码的扩展难以忍受。如何创建委托(delegate)或委托(delegate)集合? - 谁的事件可以触发各种功能?

编辑:这些功能彼此不依赖。仅移动移动。旋转仅旋转等等。MoveRotate 只有一个实例可以影响一个组件。

class MoveClass : MonoBehaviour
{
#region Move
//to ensure only one mover coroutine can be active.
public IEnumerator moveRoutine = null;
/// <summary>
/// Moves a UnityEngine.GameObject from position A to position B over timeToReachDestination.
/// Uses Coroutines.
/// </summary>
/// <param name="from"></param>
/// <param name="to"></param>
/// <param name="overTime"></param>
public void Move(Transform from, Transform to, float overTime)
{
//pull off this shit to ensure only once it will be executed.
if (moveRoutine != null)
{
StopCoroutine(moveRoutine);
}
moveRoutine = _Move(from, to, overTime);
StartCoroutine(moveRoutine);
//StartCoroutine(_Move(from, to, overTime));
}
IEnumerator _Move(Transform from, Transform to, float overTime)
{
Vector2 original = from.position;
float timer = 0.0f;
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;
}
if(event != null)
{
event(/*parameters*/);
//or loop through the events?
}
}
#endregion
}

最佳答案

似乎您想要在协程结束时进行回调。

IEnumerator _Move(Transform from, Transform to, float overTime, Action /*<Parameter>*/ onCompletion = null)
{
// Your current code

if(onCompletion!= null)
{
onCompletion(/*parameters*/);
//or loop through the events?
}
}

编辑:添加了 onCompletion = null 所以它有默认参数。

考虑到您可能有不同的回调参数列表,您会想出各种重载。公共(public)代码将移动到在所有不同重载中调用的方法,只有最后一部分会有所不同:

void MoveItem(Transform from, Transform to, float overTime)
{
float step = Vector2.Distance(original, to.position) * (Time.deltaTime / overTime);
from.position = Vector2.MoveTowards(from.position, to.position, step);
}
IEnumerator _Move(Transform from, Transform to, float overTime, Action onCompletion = null)
{
Vector2 original = from.position;
float timer = 0.0f;
while (timer < overTime)
{
MoveItem(from, to, overTime);
timer += Time.deltaTime;
yield return null;
}
if(event != null)
{
event();
}
}

IEnumerator _Move(Transform from, Transform to, float overTime, Action <float>onCompletion = null)
{
Vector2 original = from.position;
float timer = 0.0f;
while (timer < overTime)
{
MoveItem(from, to, overTime);
timer += Time.deltaTime;
yield return null;
}
if(event != null)
{
event(10.0f);
}
}

您可以灵活地为 MoveItem 方法提供委托(delegate),这样您就可以传递任何移动方法(移动的形状可以是线性的、指数的等等)。

关于c# - 将不同的功能收集到一个委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42068264/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com