StartCoroutine() 似乎不是 运行 例程
StartCoroutine() seems to not run the routine
我有一个 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 () { }
}
我不知道那是怎么发生的,但我注意到如果我在调用者脚本的 Update() 方法中调用它 - 它有效!!!
我有一个 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 () { }
}
我不知道那是怎么发生的,但我注意到如果我在调用者脚本的 Update() 方法中调用它 - 它有效!!!