- Home /
As I can make a timer?
I need to execute a function after some time. How can I ?
Comment
Answer by whydoidoit · Jun 05, 2012 at 05:28 PM
Simply use Invoke or InvokeRepeating on your behaviour.
http://unity3d.com/support/documentation/ScriptReference/MonoBehaviour.Invoke
Answer by bompi88 · Jun 05, 2012 at 09:21 PM
I usually do something like this, because then I can easily pass parameters to it. You can simply invoke any function after an amount of seconds with this line:
// Start a coroutine ExecuteIn, pass methodname, seconds to wait, and parameters in an object.
StartCoroutine("ExecuteIn", new object[3] { "DoSomething", 0.5f, new object[2]{ "I love this", 100f}});
like in this script:
using UnityEngine;
using System.Collections;
using System.Reflection;
using System;
public class example : MonoBehaviour {
void Start () {
// Start a coroutine ExecuteIn, pass methodname, seconds to wait, and parameters in an object.
StartCoroutine("ExecuteIn", new object[3] { "DoSomething", 0.5f, new object[2]{ "I love this", 100f}});
}
// Your function you will execute after x seconds
void DoSomething (string s, float t) {
// Gets current executed method information. This is just for this example.
MethodBase methodIn = MethodBase.GetCurrentMethod();
Debug.Log("Executed method " + methodIn.Name + " at " + Time.time); // prints ca. 0.5f
Debug.Log(s + ": " + t + " %");
}
// Gets the method name, and calls the method after the amount of time specified.
IEnumerator ExecuteIn(object[] myMethodInfo) {
Debug.Log("Starts timer at " + Time.time + " and waits before executing method: " + myMethodInfo[0]);
// Gets the method information from string
MethodInfo method = this.GetType().GetMethod((string)myMethodInfo[0], BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
// waits for x seconds
yield return new WaitForSeconds((float)myMethodInfo[1]);
// if method found: invoke the method
if (method != null)
{
method.Invoke(this, (object[]) myMethodInfo[2]);
} else {
Debug.LogError("Method not found");
}
}
}
Your answer
Follow this Question
Related Questions
How to work a real life timer? 2 Answers
timer that can be reset 1 Answer
The timer starts after a collision with an object 1 Answer