How to make an object fall after a delay?,How to get the object to fall after a certain time
Hi, so i am creating an endless runner game and i want one of my game objects to fall from the top of the screen after a set time. I have a code for the falling and one for the delay but together they don't seem to work. Any suggestions would be highly appreciated.
public class Fall : MonoBehaviour { public float fallSpeed = 4.0f; //how fast the object fall
[SerializeField]
GameObject _pigeon;
// delays the method defined in the code
void Start()
{
Invoke("DisplayPigeon", 2);
}
//unhides the pigeon gameobject
public void DisplayPigeon()
{
_pigeon.SetActive(true);
}
//should move the pigeon down the screen
void Update()
{
transform.Translate(Vector3.down * fallSpeed * Time.deltaTime, Space.World);
}
}
Is the pigeon not displaying or does it display but is already off screen? If so it's possible that the pigeon is translating while not visible or is translating very quickly and moves off screen before you see it. You could try adding a check "if(_pigeoon.activeself == true)" in your Update before calling translate, and also playing with the fall speeds.
Answer by LogCatGames · Jun 10, 2019 at 09:31 AM
Here I upgraded your script to work fine normally... Hope this will help... To make the thing you want you can use Coroutine :
public class Fall : MonoBehaviour { public float fallSpeed = 4.0f; //how fast the object fall
[SerializeField]
GameObject _pigeon;
private bool CanFall;
public float TimeBeforeFall = 5; // The value before falling for exemple 5
// delays the method defined in the code
void Start()
{
Invoke("DisplayPigeon", 2);
StartCoroutine(ReadyToFall());
}
//unhides the pigeon gameobject
public void DisplayPigeon()
{
_pigeon.SetActive(true);
}
//should move the pigeon down the screen
void Update()
{
if(CanFall == true)
{
transform.Translate(Vector3.down * fallSpeed * Time.deltaTime, Space.World);
}
}
IEnumerator ReadyToFall ()
{
CanFall = false;
yield return new WaitForSeconds(TimeBeforeFall);
CanFall = true;
}
}
You can aswell modify it to put the start coroutine somewhere else...
Your answer
Follow this Question
Related Questions
I create material with script but it does not render right 0 Answers
Creating Splines from empties in script 0 Answers
How can i rotate all the child objects together at the same time ? 1 Answer
How can i give another name/number to the created Plane object name ? 0 Answers
How can i create List of maps from each Map class ? 0 Answers