user8531441
user8531441

Reputation:

Timer function doesnt work (Unity+C#)

I wrote my own function of rotating a group of objects. I want ot make a new one, with smooth rotating, so I need a timer. I have tried to call Timer a few times, but it doesnt work. Here's my code:

public class rotate_around : MonoBehaviour 
{
    public Transform sphere;        

    // Update is called once per frame
    void Update ()
    {
        if (Input.GetKeyDown(KeyCode.RightArrow))
        {
            sphere.RotateAround(new Vector3(3, 3, 3), new Vector3(0, 1, 0), 45);
            timer();
        }
    }        

    public IEnumerator timer()
    {
        yield return new WaitForSeconds(5);
        // actually I tried to add Debug.Log("blahblahblah") here, but it still didnt output anything
    }
}

Upvotes: 0

Views: 105

Answers (3)

zambari
zambari

Reputation: 5035

As mentioned before, the correct way to start a coroutine is StartCoroutine(timer());

from your code it isn't clear what you are trying to achieve, currently you do nothing after waiting those five seconds

Also you probably should implement some sort of mechanism that prevents user from spamming coroutines. You can set a bool flag, or hold reference to the coroutine you started - I often do

Coroutine myRoutine; // in global scope
if (myRoutine==null) myRoutine=StartCoroutine(timer()); // in event handler

myRoutine will null itself when its finished

Upvotes: 0

Alexander M.
Alexander M.

Reputation: 31

StartCoroutine("timer", true);

would be the best way to do it!

timer() would just call a normal method. IEnumerator works different.

Upvotes: 1

Daxtron2
Daxtron2

Reputation: 1309

Try using StartCoroutine(timer()); instead of just timer();

Upvotes: 3

Related Questions