I want an object to rotate after a delay. I tried using StartCoroutine
, yield
and WaitForSeconds
, but failed. How can I do it?
-
\$\begingroup\$ If you have additional questions, you should ask them as new questions, instead of editing one you've previously asked. \$\endgroup\$– ProblematicCommented Nov 6, 2015 at 21:05
4 Answers
You could create a variable for example called timer
of type float and make it equal to the amount of seconds you would like to wait, then in the Update()
function subtract Time.deltaTime
from your timer
variable. Afterwards use if statement to check if the timer
variable is equal to zero, if so rotate the object.
-
\$\begingroup\$ I do not get errors anymore, but it still has no effect \$\endgroup\$ Commented Aug 27, 2015 at 20:10
-
\$\begingroup\$ Comments are not for extended discussion; this conversation has been moved to chat. \$\endgroup\$– HouseCommented Aug 28, 2015 at 0:35
Multiple choices, but you will have to use Coroutine sometimes, so try to figure out why its not working here.
My tips : careful to not call StartCoroutine in Update() without protection.
Exemple:
private bool enter = false;
Update() {
if (enter == false)
StartCoroutine(your_timer());
}
IEnumerator your_timer() {
enter = true;
Debug.Log("Your enter Coroutine at" + Time.time);
yield return new WaitForSeconds(2.0f);
enter = false;
}
From here
public void Invoke(string methodName, float time);
Invokes the method methodName in time seconds.
There is a restriction that the method needs to take no parameters and return void
, so you should wrap your rotation in another function, like so:
void delayedRotation() {
transform.Rotate (new Vector3 (0, 0, 1) * Time.deltaTime);
}
and then adjust your code:
if (isRolling)
{
transform.position += new Vector3 (0,1,2)
Invoke("delayedRotation", 0.5f);
}
void Update(){
if(INSERT_CONDITION_HERE){
StartCoroutine(Timer);
}
}
Then
IEnumerator Timer(){
yield return new WaitForSeconds(Time);
CODEGOESHERE
}