我在 Unity 2D 项目中有一个路点系统,其中 GameObject 将按顺序跟随每个路点,然后重复该过程,我希望 GameObject 在每个点停止一段固定的时间,我认为我可以实现这使用协程但不完全确定如何实现这一点,到目前为止我所做的是创建一个名为 WaitAtPoint 的协程,然后在每个航路点移动时调用它但无济于事,我不确定我做错了什么。
public class BrainBoss : MonoBehaviour {
[SerializeField]
Transform[] waypoints;
[SerializeField]
float moveSpeed = 2f;
int waypointIndex = 0;
// Start is called before the first frame update
void Start()
{
transform.position = waypoints[waypointIndex].transform.position;
}
// Update is called once per frame
void Update()
{
Move();
}
void Move()
{
transform.position = Vector2.MoveTowards(transform.position,
waypoints[waypointIndex].transform.position, moveSpeed * Time.deltaTime);
if(transform.position == waypoints[waypointIndex].transform.position)
{
StartCoroutine(WaitAtPoint());
waypointIndex += 1;
}
if(waypointIndex == waypoints.Length)
{
waypointIndex = 1;
}
}
IEnumerator WaitAtPoint()
{
yield return new WaitForSeconds(3f);
}
最佳答案
您在每次更新时都调用 Move,您也可以多次调用该 StartCoroutine,所以我建议使用变量来查看您是否应该更新移动
public class BrainBoss : MonoBehaviour
{
[SerializeField]
Transform[] waypoints;
[SerializeField]
float moveSpeed = 2f;
int waypointIndex = 0;
private bool shouldMove = true;
// Start is called before the first frame update
void Start() {
transform.position = waypoints[waypointIndex].transform.position;
}
// Update is called once per frame
void Update() {
if (this.shouldMove) {
Move();
}
}
void Move() {
transform.position = Vector2.MoveTowards(transform.position,
waypoints[waypointIndex].transform.position, moveSpeed * Time.deltaTime);
if (transform.position == waypoints[waypointIndex].transform.position) {
StartCoroutine(WaitAtPoint(3));
waypointIndex += 1;
}
if (waypointIndex == waypoints.Length) {
waypointIndex = 1;
}
}
IEnumerator WaitAtPoint(int seconds) {
this.shouldMove = false;
int counter = seconds;
while (counter > 0) {
yield return new WaitForSeconds(1);
counter--;
}
this.shouldMove = true;
}
关于c# - 在路点等待统一 C# 中的时间量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58113719/