Eugene Eugene - 1 year ago 76
C# Question

Calling StartCoroutine() is not working

I have a Sphere prefab which is just sphere with MoveSphere script attached to it. It has

Rotate()
method which starts coroutine. The Rotate() method make the sphere move along circle trajectory. The problem is when i call
Rotate()
method inside
Start()
method of MoveSphere script it works fine, but when i try to call it inside Start method of a GameController script - it doesn't work (the sphere stays at the same place). Here is my code for MoveSphere and GameController scripts:

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 () { }
}

Answer Source

I don't know how that happened, but i noticed that if i call it inside Update() method of caller script - it works!!!.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download