我有各种工作正常的方法,但我只想在延迟后才调用它们。为了避免为所有这些 编写不同的方法,我认为以某种方式Invoke
它们更为有益。我制作了这些方法,以便它们排除 Unity
的 timeScale
,因此它们总是等待 Real seconds
,使用自定义构建的短函数。
WaitForRealSeconds
:
public class WaitForRealSecondsClass
{
#region Wait for real seconds
public Coroutine WaitForRealSeconds(float aTime, MonoBehaviour mono)
{
return mono.StartCoroutine(_WaitForRealSeconds(aTime));
}
private IEnumerator _WaitForRealSeconds(float aTime)
{
while (aTime > 0.0f)
{
aTime -= Mathf.Clamp(Time.unscaledDeltaTime, 0, 0.2f);
yield return null;
}
}
#endregion
}
我希望调用
我的移动函数
的方式:
public void InvokeAnim(float timeBeforeStart, Action<MonoBehaviour> MoveFunction, MonoBehaviour mono)
{
if (moveRoutine != null)
{
mono.StopCoroutine(moveRoutine);
}
moveRoutine = _InvokeAnim(timeBeforeStart, MoveFunction, mono);
}
IEnumerator _InvokeAnim(float timeBeforeStart, Action<MonoBehaviour> MoveFunction, MonoBehaviour mono)
{
yield return new WaitForRealSecondsClass().WaitForRealSeconds(timeBeforeStart, mono);
MoveFunction(mono);
}
Move(MonoBehaviour mono)
本身:
public void Move(MonoBehaviour mono)
{
if (moveRoutine != null)
{
mono.StopCoroutine(moveRoutine);
}
moveRoutine = _Move(from, to, overTime, mono);
mono.StartCoroutine(moveRoutine);
}
我测试和工作的是 Move
本身,我在另一个项目中使用的 WaitForRealSeconds
在游戏停止时等待 UI,当时没问题。
正如我所说,我有很多方法可以调用,所有方法都返回 void
并有一个参数 MonoBehaviour
。目前它没有做任何事情,我不知道为什么。
最佳答案
去他的吧,我太笨了以至于忘记实际启动那个协程。
在我的调用
中:
public void InvokeAnim(float timeBeforeStart, Action<MonoBehaviour> MoveFunction,
MonoBehaviour mono)
{
if (moveRoutine != null)
{
mono.StopCoroutine(moveRoutine);
}
moveRoutine = _InvokeAnim(timeBeforeStart, MoveFunction, mono);
mono.StartCoroutine(moveRoutine); //one line was missing
}
IEnumerator _InvokeAnim(float timeBeforeStart, Action<MonoBehaviour> MoveFunction,
MonoBehaviour mono)
{
yield return new WaitForRealSecondsClass().WaitForRealSeconds(timeBeforeStart, mono);
MoveFunction(mono);
}
关于C# 自定义 Invoke 方法调用各种其他方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42133408/