【问题标题】:StartCoroutine() seems to not run the routineStartCoroutine() 似乎没有运行例程
【发布时间】:2017-12-29 01:03:00
【问题描述】:

我有一个 Sphere 预制件,它只是一个附有 MoveSphere 脚本的球体。它具有启动协程的Rotate() 方法。 Rotate() 方法使球体沿圆形轨迹移动。问题是当我在 MoveSphere 脚本的 Start() 方法中调用 Rotate() 方法时它工作正常,但是当我尝试在 GameController 脚本的 Start 方法中调用它时 - 它不起作用(球体保持在同一个地方)。这是我的 MoveSphere 和 GameController 脚本代码:

public class MoveSphere : MonoBehaviour
{
    // ...some fields

    void Start()
    {
        rb = GetComponent<Rigidbody>();

        // if i uncomment next line of code - it works fine
        // Rotate();
    }

    public void Rotate()
    {
        StartCoroutine(rotate());
    }

    void Update() { }

    public IEnumerator rotate()
    {
        int n = (int)(360 / dAngle);
        float da = 360f / n;
        vAmp = radius * da * Mathf.Deg2Rad / dt;
        currentAngle = 0;
        for (int i = 0; i < n; i++)
        {
            Vector3 pos = getPosition(currentAngle);
            currentAngle += da;
            rb.position = pos;
            yield return new WaitForSeconds(dt);
        }
    }

    //...some mathematical methods
}

public class GameController : MonoBehaviour
{
    public GameObject obj;
    public int numOfInstances;

    // Use this for initialization
    void Start ()
    {
        GameObject sphere1 = Instantiate(obj, new Vector3(-5,0,-2), Quaternion.identity);

        // this one doesn't work
        sphere1.GetComponent<MoveSphere>().Rotate();
    }

    void Update () { }
}

【问题讨论】:

  • MoveSphere 是预制件还是简单地附加到场景中的现有对象?
  • 球体是预制件。
  • 请解释一下“它不起作用”是什么意思。你有什么错误吗?你确定协程没有启动(添加一个简单的Debug.Log 来检查)?我几乎可以肯定你有一个NullReferenceException,因为rb 是空的。您必须在 Awake 方法中调用 rb = GetComponent&lt;Rigidbody&gt;();,而不是 MoveSphere 类的 Start 之一。
  • Rotate() 方法使球体沿圆形轨迹移动。 “它不起作用”意味着球体停留在同一个地方。
  • 我也没有看到dt的定义

标签: c# unity3d game-engine coroutine


【解决方案1】:

我不知道这是怎么发生的,但我注意到如果我在调用者脚本的 Update() 方法中调用它 - 它可以工作!!!。

【讨论】:

    猜你喜欢
    • 2015-09-22
    • 2021-11-27
    • 1970-01-01
    • 2022-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多