c# - 统一,C# |如何在方法之间设置等待时间?

标签 c# unity-game-engine 2d

我的目标:让我的蜗牛看起来像是在自行移动。 示例:向右走几秒钟,向左走几秒钟,在一个地方停留几秒钟。

当前状态:当我尝试使用 WaitForSeconds 时,Snail 静止在一处

没有WaitForSeconds,我的蜗牛可以成功地来回改变方向(除非做得非常快)

我昨天才开始学习Unity和C#。任何提示/建议都会有很大帮助,即使它不是我原来的问题。 如果我还能做些什么来帮助您,请告诉我! :)

using UnityEngine;
using System.Collections;

public class SnailMove : MonoBehaviour {
void Start()
{

}
// Use this for initialization
void Update () 
{
    Waiting();
}

// Update is called once per frame
void Movement () 
{

    int direct = Random.Range(-1, 2);
    if (direct == 1) 
    {
        transform.Translate(Vector3.left * 1f * Time.deltaTime);
        transform.eulerAngles = new Vector2(0,180);
    }
    if (direct == -1)
    {
        transform.Translate(Vector3.left * 1f * Time.deltaTime);
        transform.eulerAngles = new Vector2(0,0);
    }
}
  IEnumerator Waiting()
    {
    Movement ();
    yield return new WaitForSeconds (5);
    }
}

最佳答案

协程需要以 StartCoroutine 启动。从您的描述来看,您似乎想要这样的东西:

using UnityEngine;
using System.Collections;

public class SnailMove : MonoBehaviour
{
    public float speed = 1f;
    int direction = 0;
    void Start()
    {
        StartCoroutine(ChangeDirection());
    }

    void Update () 
    {
        if (direction == 1) 
        {
            transform.Translate(Vector3.left * speed * Time.deltaTime);
            transform.eulerAngles = new Vector2(0,180);
        }
        else if (direction == -1)
        {
            transform.Translate(Vector3.left * speed * Time.deltaTime);
            transform.eulerAngles = new Vector2(0,0);
        }
    }

    IEnumerator ChangeDirection()
    {
        while(true)
        {
            yield return new WaitForSeconds (5);
            direction = Random.Range(-1, 2); // returns "-1", "0" or "1"
        }
    }
}

关于c# - 统一,C# |如何在方法之间设置等待时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27031778/

相关文章:

c# - 将视频上传到特定 channel /Youtube

c# - linq-to-sql .All() 或 .Any() 查找匹配条件的所有项目

wpf - 在 WPF 中的绘图和形状之间进行选择

javascript - html5 Canvas strokeStyle?

c# - Unity 文本事件在编辑器中触发,但不在构建中触发

c - 扫描到二维数组,然后将其传递给函数 - C

c# - 在调试处理器中定义终结器以定位未显式调用 Dispose 的任何情况

c# - 关注点分离——DAO、DTO 和 BO

ios - Unity iOS IPv6 - IL2CPP UnityEngine.Experimental.Networking 崩溃

c# - 通过unity从服务器获取数据