- Home /
i need to delay an action but my code isnt working
I need to delay the action inside the OnCollisionEnter so that gravity turns on a second after my player hits the object but yield WaitForSeconds is not working. am I using it incorrectly or is there another way that this needs to be done? This is the code and I would much appreciate if someone would edit it. As of now the gravity turns on immediately when collided with but i want it to be delayed a second after collision before gravity is turned back on.
#pragma strict
function OnCollisionEnter(Player)
{
yield WaitForSeconds (2);
rigidbody.useGravity = true;
}
I'm not familiar with UnityScript, but maybe OnCollisionEnter can't be called as a coroutine. Try calling a function that does the yield internally, something like:
#pragma strict
function OnCollisionEnter(Player)
{
WaitAndSetGravity();
}
function WaitAndSetGravity()
{
yield WaitForSeconds (2);
rigidbody.useGravity = true;
}
I see what you are saying and I am extremely new to coroutines and will look into this answer but this code directly does not work. But i never considered that OnCollisionEnter might not work as a coroutine so thank you
Answer by Positive7 · Aug 03, 2015 at 08:29 PM
#pragma strict
function OnCollisionEnter(col : Collision)
{
if(col.gameObject.tag == "Player"){
yield WaitForSeconds (2);
GetComponent.<Rigidbody>().useGravity = true;
}
}
this does the same thing as before as it initiates gravity immediately ins$$anonymous$$d of waiting 2 seconds and I have absolutely no idea what is wrong with it but thank you for trying to help
$$anonymous$$aybe a stupidish question but did you turn off gravity on the object Rigidbody? I tested above script and it worked fine.
yes for this object that the player is to land on, the gravity is off
Ohh. so it's something you jump on? Does Player uses Gravity? Is it possible it starts moving because player pushes it down..
#pragma strict
function OnCollisionEnter(col : Collision)
{
if(col.gameObject.tag == "Player"){
GetComponent.<Rigidbody>().is$$anonymous$$inematic = true;
yield WaitForSeconds (5);
GetComponent.<Rigidbody>().is$$anonymous$$inematic = false;
GetComponent.<Rigidbody>().useGravity = true;
}
}
it is something i jump on what happens with the original code is that it starts moving as soon as i jump on it. what I want it to do is start moving two seconds after i jump on it
Your answer
Follow this Question
Related Questions
Reloading delay problem.. 0 Answers
Problem with yield 0 Answers
Delay in Instantiate only runs once 2 Answers
yield WaitForSeconds 1 Answer
Calling a function in another script not working with yield 1 Answer