我的目标:让我的蜗牛看起来像是在自行移动。 示例:向右走几秒钟,向左走几秒钟,在一个地方停留几秒钟。
当前状态:当我尝试使用 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/