【发布时间】: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<Rigidbody>();,而不是MoveSphere类的 Start 之一。 -
Rotate() 方法使球体沿圆形轨迹移动。 “它不起作用”意味着球体停留在同一个地方。
-
我也没有看到
dt的定义
标签: c# unity3d game-engine coroutine