co pro Games co pro Games - 3 months ago 14
C# Question

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.

Answer

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");
}