co pro Games
co pro Games

Reputation: 5

How to run command then timer is ended ? C#

I dont know how to make a command run then the timer stops here is the code :

using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
using System.Threading;
using System;

public class introtogamescript : MonoBehaviour
{
    public class Example
    {
        public static void Main()
        {
            // Create an instance of the Example class, and start two
            // timers.
            Example ex = new Example();
            ex.StartTimer(7000);
        }

        public void StartTimer(int dueTime)
        {
            Timer t = new Timer(new TimerCallback(TimerProc));
            t.Change(dueTime, 0);
        }

        private void TimerProc(object state)
        {
            // The state object is the Timer object.
            Timer t = (Timer)state;
            t.Dispose();
            SceneManager.LoadScene(2);
        }
    }
}

Thanks for the help.

Upvotes: 0

Views: 966

Answers (3)

Bamdad
Bamdad

Reputation: 856

You can also use Invoke(string methodName, float callDelay)

Example:

void SomeMethod()
{
   Invoke("OtherMethod",3.5f);
}

//It should be called 3.5 seconds after SomeMethod
void OtherMethod()
{
    print(something);
}

And you can not invoke any parameter

Upvotes: 0

Umair M
Umair M

Reputation: 10740

You can use coroutines like this:

public void  WaitAndExecute(float timer, Action callBack = null)
{
    StartCoroutine(WaitAndExecute_CR(timer,callBack));
}

IEnumerator WaitAndExecute_CR(float timer, Action callBack = null)
{
    yield return new WaitForSeconds(timer);

    if (callBack != null)
    {
        callBack();
    }
}


void Start()
{
    WaitAndExecute(5,() => {Debug.Log("This will be printed after 5 seconds");});

    WaitAndExecute(10,JustAnotherMethod);
}

void JustAnotherMethod()
{
    Debug.Log("This is another way to use callback methods");
}

Upvotes: 1

Tyronne
Tyronne

Reputation: 135

When you start the timer use lambdas or anonymous delegate - this way you will have the timer as closure.

Upvotes: 0

Related Questions