我正在制作无尽的亚军游戏,我希望我的代码的一部分等待几秒钟,我该怎么做?问题在于,当新地形的开始边缘碰到相机视图的底部时,它将删除地形。
void Start()
{
StartCoroutine(Example());
}
IEnumerator Example()
{
yield return new WaitForSeconds(5);
}
}
这是我希望回收平台功能在几秒钟后执行的代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlatformManager : MonoBehaviour
{
[SerializeField]
private GameObject[] _platformPrefabs;
[SerializeField]
private int _zedOffset;
// Start is called before the first frame update
void Start()
{
for (int i = 0; i < _platformPrefabs.Length; i++)
{
Instantiate(_platformPrefabs[i], new Vector3(0, 0, i * 4), Quaternion.Euler(0, 90, 0));
_zedOffset += 4;
}
}
// i want this to wait
public void RecyclePlatform(GameObject Platform)
{
Platform.transform.position = new Vector3(0, 0, _zedOffset);
_zedOffset += 4;
}
}
recyclePlatform函数在执行之前需要等待
如果您只是想让线程等待-
System.Threading.Thread.Sleep(milliseconds);
将其转换为Unity Coroutine。
private IEnumerator RecyclePlatform(GameObject Platform)
{
yield return new WaitForSeconds(numSecondsToWait); # we can use floats to specify more accurate times
Platform.transform.position = new Vector3(0, 0, _zedOffset);
_zedOffset += 4;
}
然后我们随时随地开始这样的例程。
StartCoroutine(RecyclePlatform);
您可以使用它来等待您想要等待的任何功能或动作。如果要使用异步等待:
public static async void DoActionAfterSecondsAsync(Action action, float seconds)
{
await Task.Delay(TimeSpan.FromSeconds(seconds));
action?.Invoke();
}
如果要使用协程:
public IEnumerator void DoActionAfterSecondsRoutine(Action action, float seconds)
{
yield return new WaitForSecondsRealtime(seconds);
action?.Invoke();
}
我建议您为此使用实用程序类。看起来像这样。
public static class CooldownManager
{
private class HiddenMonobehaviour : MonoBehaviour { }
private static readonly MonoBehaviour mono;
static CooldownManager()
{
GameObject obj = new GameObject("CooldownManager");
UnityEngine.Object.DontDestroyOnLoad(obj);
mono = obj.AddComponent<HiddenMonobehaviour>();
}
public static Coroutine Cooldown(float cooldownDuration, Action action)
{
return mono.StartCoroutine(InternalCooldown(cooldownDuration, action));
}
private static IEnumerator InternalCooldown(float cooldownDuration, Action action)
{
yield return new WaitForSeconds(cooldownDuration);
action.Invoke();
}
}
使用它,您可以编写:
public class Example : MonoBehaviour
{
void Start()
{
Cooldown(2, () => RecyclePlatform(gameObject));
}
void RecyclePlatform(GameObject Platform)
{
Platform.transform.position = new Vector3(0, 0, _zedOffset);
_zedOffset += 4;
}
}
只需将代码放在协程中,并添加超时时间
public void RecyclePlatform(GameObject Platform)
{
StartCoroutine(RecyclePlatformCoroutine(Platform));
}
private IEnumerator RecyclePlatformCoroutine(GameObject Platform)
{
yield return new WaitForSeconds(5);
Platform.transform.position = new Vector3(0, 0, _zedOffset);
_zedOffset += 4;
}