C# startcroutine()似乎没有运行该例程
我有一个球体预制,它只是一个球体,附带了MoveSphere脚本。它具有启动协同程序的C# startcroutine()似乎没有运行该例程,c#,unity3d,game-engine,coroutine,C#,Unity3d,Game Engine,Coroutine,我有一个球体预制,它只是一个球体,附带了MoveSphere脚本。它具有启动协同程序的Rotate()方法。Rotate()方法使球体沿圆轨迹移动。问题是,当我调用MoveSphere脚本中的Rotate()method insideStart()method时,它工作得很好,但当我尝试在GameController脚本的Start方法中调用它时,它不起作用(球体保持在同一位置)。以下是我的MoveSphere和GameController脚本代码: public class MoveSpher
Rotate()
方法。Rotate()方法使球体沿圆轨迹移动。问题是,当我调用MoveSphere脚本中的Rotate()
method insideStart()
method时,它工作得很好,但当我尝试在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
}
公共类MoveSphere:MonoBehavior
{
//…一些领域
void Start()
{
rb=GetComponent();
//如果我取消注释下一行代码,它可以正常工作
//旋转();
}
公共空间(英文)
{
start例程(rotate());
}
无效更新(){}
公共IEnumerator旋转()
{
int n=(int)(360/悬挂);
浮球da=360f/n;
鞋面=半径*da*Mathf.Deg2Rad/dt;
电流角=0;
对于(int i=0;i
公共类游戏控制器:单行为
{
公共游戏对象obj;
公共事务实例;
//用于初始化
无效开始()
{
GameObject sphere1=实例化(obj,新向量3(-5,0,-2),四元数.identity);
//这个不行
sphere1.GetComponent().Rotate();
}
无效更新(){}
}
我不知道这是怎么发生的,但我注意到,如果我在调用方脚本的Update()方法中调用它,它会工作 MoveSphere
是预设的还是仅仅附加到场景中的现有对象?Sphere是预设的。请解释“它不工作”是什么意思。你有什么错误吗?您确定协同程序没有启动(添加一个简单的Debug.Log
来检查)?我几乎可以肯定您有一个NullReferenceException
,因为rb
是空的。您必须调用rb=GetComponent()
在Awake方法中,而不是MoveSphere
类的开始部分。Rotate()方法使球体沿圆轨迹移动。“它不工作”意味着球体停留在同一个位置。我也没有看到dt
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 () { }
}