How to make game wait before strats? - c#

I am trying to do when i run the game it wait 3s before it starts in Unity.
I put all gameobjetc in a empty object with code:
[SerializeField]
private float seconds = 3f;
private void Start()
{
StartCoroutine(Wait());
}
private IEnumerator Wait()
{
Time.timeScale = 0f;
yield return new WaitForSeconds(seconds);
Time.timeScale = 1f;
}
And when I start the game its just frozen nothing is counting down.

Because WaitForSeconds corresponds to the time in the game and follows Time.scale, So when you set Time.Scale to 0, no time passes. Use WaitForSecondsRealtime to resolve this issue, This method works independently of Time.Scale, and if you use Slow-Motion or Freeze effects in your game, consider this one:
yield return new WaitForSecondsRealtime(seconds);

You should be able to solve your issue by removing the Time.timeScale = 0f; code. Let me explain why.
If you decrease the timescale to say 0.5, you are increasing your time by two. So your 3 / 0.5 = 6 seconds.
When you are setting your timescale to 0 you are essentially pausing your app because you are making your app wait infinitely.
So if you remove the timeScales like this it should work fine:
private IEnumerator Wait()
{
yield return new WaitForSeconds(seconds);
}

Related

How come this simple random jumping script doesn't work?

so I am currently creating a simple platformer enemy that is meant to jump at random intervals, I want the enemy to do it every 2-5 seconds. While this script should work in theory (I cannot see anything wrong with it) when I run Unity, the enemy just doesn't move. I added in the Debug.Log() lines to try to figure if it was running but the force was too small or to see if it was getting stuck in the waiting state, however the console repeats nothing but "Not Waiting". So it never even runs the Delay in the first place.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class JumperMovement : MonoBehaviour
{
Rigidbody2D rb;
public float jumpForce;
bool jump = false;
bool waiting = false;
private void Awake()
{
rb = gameObject.GetComponent<Rigidbody2D>();
}
private void Update()
{
if (jump)
{
Vector2 motion = new Vector2(0f, jumpForce);
rb.AddForce(motion, ForceMode2D.Impulse);
Debug.Log("Jumping");
jump = false;
Delay();
} else if (!waiting)
{
Debug.Log("Not Waiting");
Delay();
}
}
IEnumerator Delay()
{
waiting = true;
int delay = Random.Range(2, 6);
Debug.Log("Waiting");
yield return new WaitForSeconds(delay);
jump = true;
waiting = false;
}
}
I also tried to just put all the code into a loop in the co-routine but I got the same result. I've not used them much so don't know much about them so if someone can explain why this doesn't work as well that would be super useful.
IEnumerator Delay()
{
while (true)
{
int delay = Random.Range(2, 6);
yield return new WaitForSeconds(delay);
Vector2 motion = new Vector2(0f, jumpForce);
rb.AddForce(motion, ForceMode2D.Impulse);
}
}
There's a couple of things causing issues here:
Coroutines should be started with the StartCoroutine(coroutine) method, else they will be ran as normal code, which is why waiting seems to always be false. (Delay() is ran without pausing, meaning waiting = true and waiting = false happens immediately)`
RigidBody.AddForce is a physics operation, meaning it should be ran within the FixedUpdate method, and not in the normal Update method. If you want to run AddForce inside the Coroutine, use yield return new WaitForFixedUpdate()

I'm trying to implement a time delay in Unity. I have done it using while loop, for loop and coroutines, but none of them seem to work

Here is my code.. I have explained the issue after..
public bool isPipeActive;
[SerializeField] private float timer;
void Start()
{
isPipeActive = false;
timer = 0f;
}
void FixedUpdate()
{
if (Input.GetKeyDown(KeyCode.Backspace))
{
isPipeActive = !isPipeActive; //bool flag invert
}
if (isPipeActive == true) //start pipe animations
{
for (int j = 0; j < ParentOf_arrow.transform.childCount; j++)
{
Initiate_arrow_FLOW_INDICATOR(j);
StartCoroutine(Time_Delay());
//while (timer < 1.0f)
for (timer = 0f; timer < 2.0f; timer += Time.fixedDeltaTime)
{
//just a blank function to see if it creates a delay..
timer += Time.fixedDeltaTime;
}
//timer = 0f;
}
}
}
IEnumerator Time_Delay()
{
yield return new WaitForSeconds(2f);
Debug.Log("2s delay initiated");
}
Initiate_arrow_FLOW_INDICATOR(j) visibly changes the color of one 3D arrow in a sequence of 3D arrows (arrow1, then arrow2, etc) to show direction. something like this.. i just want to add a time delay in between each color change, but none of the attempts i've made seem to create a time delay when i enter play mode and press Backspace key.
the colors flash extremely fast. There is no waiting between color changes whatsoever.. even when running the coroutine, while loop and for loop together :(
What is going on and how do i fix it??
The issue with the for loop is that you aren't waiting for the actual time between fixed updates and rather using the time between the last fixed update and adding it as fast as your CPU will until timer is larger than 2.
The coroutine will wait 2 seconds before logging it's output.
You need to put your arrow change code in the coroutine, because the Coroutine essentially works in "parallel" to your FixedUpdate.
So either do:
void FixedUpdate()
{
timer += Time.deltaTime;
if(timer >= 2.0f) {
//arrow thingy
timer = 0;
}
}
or in the Coroutine:
IEnumerator TimeDelay()
{
yield return new WaitForSeconds(2f);
//arrow thingy
}
In this state the FixedUpdate version will loop indefinitely and call arrow thingy roughly each two seconds, and the Coroutine will do so once.
A quick side note you should probably use Update and DeltaTime for this and not FixedUpdate with FixedDeltaTime.

Move object from one position to the target position in x seconds, complete an action and repeat (Unity 2D c#) [duplicate]

I am learning Unity from a Swift SpriteKit background where moving a sprite's x Position is as straight forward as an running an action as below:
let moveLeft = SKAction.moveToX(self.frame.width/5, duration: 1.0)
let delayAction = SKAction.waitForDuration(1.0)
let handSequence = SKAction.sequence([delayAction, moveLeft])
sprite.runAction(handSequence)
I would like to know an equivalent or similar way of moving a sprite to a specific position for a specific duration (say, a second) with a delay that doesn't have to be called in the update function.
gjttt1's answer is close but is missing important functions and the use of WaitForSeconds() for moving GameObject is unacceptable. You should use combination of Lerp, Coroutine and Time.deltaTime. You must understand these stuff to be able to do animation from Script in Unity.
public GameObject objectectA;
public GameObject objectectB;
void Start()
{
StartCoroutine(moveToX(objectectA.transform, objectectB.transform.position, 1.0f));
}
bool isMoving = false;
IEnumerator moveToX(Transform fromPosition, Vector3 toPosition, float duration)
{
//Make sure there is only one instance of this function running
if (isMoving)
{
yield break; ///exit if this is still running
}
isMoving = true;
float counter = 0;
//Get the current position of the object to be moved
Vector3 startPos = fromPosition.position;
while (counter < duration)
{
counter += Time.deltaTime;
fromPosition.position = Vector3.Lerp(startPos, toPosition, counter / duration);
yield return null;
}
isMoving = false;
}
Similar Question: SKAction.scaleXTo
The answer of git1 is good but there is another solution if you do not want to use couritines.
You can use InvokeRepeating to repeatedly trigger a function.
float duration; //duration of movement
float durationTime; //this will be the value used to check if Time.time passed the current duration set
void Start()
{
StartMovement();
}
void StartMovement()
{
InvokeRepeating("MovementFunction", Time.deltaTime, Time.deltaTime); //Time.deltaTime is the time passed between two frames
durationTime = Time.time + duration; //This is how long the invoke will repeat
}
void MovementFunction()
{
if(durationTime > Time.time)
{
//Movement
}
else
{
CancelInvoke("MovementFunction"); //Stop the invoking of this function
return;
}
}
You can use co-routines to do this. To do this, create a function that returns type IEnumerator and include a loop to do what you want:
private IEnumerator foo()
{
while(yourCondition) //for example check if two seconds has passed
{
//move the player on a per frame basis.
yeild return null;
}
}
Then you can call it by using StartCoroutine(foo())
This calls the function every frame but it picks up where it left off last time. So in this example it stops at yield return null on one frame and then starts again on the next: thus it repeats the code in the while loop every frame.
If you want to pause for a certain amount of time then you can use yield return WaitForSeconds(3) to wait for 3 seconds. You can also yield return other co-routines! This means the current routine will pause and run a second coroutine and then pick up again once the second co-routine has finished.
I recommend checking the docs as they do a far superior job of explaining this than I could here

Move GameObject to new position overtime [duplicate]

I am learning Unity from a Swift SpriteKit background where moving a sprite's x Position is as straight forward as an running an action as below:
let moveLeft = SKAction.moveToX(self.frame.width/5, duration: 1.0)
let delayAction = SKAction.waitForDuration(1.0)
let handSequence = SKAction.sequence([delayAction, moveLeft])
sprite.runAction(handSequence)
I would like to know an equivalent or similar way of moving a sprite to a specific position for a specific duration (say, a second) with a delay that doesn't have to be called in the update function.
gjttt1's answer is close but is missing important functions and the use of WaitForSeconds() for moving GameObject is unacceptable. You should use combination of Lerp, Coroutine and Time.deltaTime. You must understand these stuff to be able to do animation from Script in Unity.
public GameObject objectectA;
public GameObject objectectB;
void Start()
{
StartCoroutine(moveToX(objectectA.transform, objectectB.transform.position, 1.0f));
}
bool isMoving = false;
IEnumerator moveToX(Transform fromPosition, Vector3 toPosition, float duration)
{
//Make sure there is only one instance of this function running
if (isMoving)
{
yield break; ///exit if this is still running
}
isMoving = true;
float counter = 0;
//Get the current position of the object to be moved
Vector3 startPos = fromPosition.position;
while (counter < duration)
{
counter += Time.deltaTime;
fromPosition.position = Vector3.Lerp(startPos, toPosition, counter / duration);
yield return null;
}
isMoving = false;
}
Similar Question: SKAction.scaleXTo
The answer of git1 is good but there is another solution if you do not want to use couritines.
You can use InvokeRepeating to repeatedly trigger a function.
float duration; //duration of movement
float durationTime; //this will be the value used to check if Time.time passed the current duration set
void Start()
{
StartMovement();
}
void StartMovement()
{
InvokeRepeating("MovementFunction", Time.deltaTime, Time.deltaTime); //Time.deltaTime is the time passed between two frames
durationTime = Time.time + duration; //This is how long the invoke will repeat
}
void MovementFunction()
{
if(durationTime > Time.time)
{
//Movement
}
else
{
CancelInvoke("MovementFunction"); //Stop the invoking of this function
return;
}
}
You can use co-routines to do this. To do this, create a function that returns type IEnumerator and include a loop to do what you want:
private IEnumerator foo()
{
while(yourCondition) //for example check if two seconds has passed
{
//move the player on a per frame basis.
yeild return null;
}
}
Then you can call it by using StartCoroutine(foo())
This calls the function every frame but it picks up where it left off last time. So in this example it stops at yield return null on one frame and then starts again on the next: thus it repeats the code in the while loop every frame.
If you want to pause for a certain amount of time then you can use yield return WaitForSeconds(3) to wait for 3 seconds. You can also yield return other co-routines! This means the current routine will pause and run a second coroutine and then pick up again once the second co-routine has finished.
I recommend checking the docs as they do a far superior job of explaining this than I could here

unity move object over time using Coroutine wont move the object precisely [duplicate]

I am learning Unity from a Swift SpriteKit background where moving a sprite's x Position is as straight forward as an running an action as below:
let moveLeft = SKAction.moveToX(self.frame.width/5, duration: 1.0)
let delayAction = SKAction.waitForDuration(1.0)
let handSequence = SKAction.sequence([delayAction, moveLeft])
sprite.runAction(handSequence)
I would like to know an equivalent or similar way of moving a sprite to a specific position for a specific duration (say, a second) with a delay that doesn't have to be called in the update function.
gjttt1's answer is close but is missing important functions and the use of WaitForSeconds() for moving GameObject is unacceptable. You should use combination of Lerp, Coroutine and Time.deltaTime. You must understand these stuff to be able to do animation from Script in Unity.
public GameObject objectectA;
public GameObject objectectB;
void Start()
{
StartCoroutine(moveToX(objectectA.transform, objectectB.transform.position, 1.0f));
}
bool isMoving = false;
IEnumerator moveToX(Transform fromPosition, Vector3 toPosition, float duration)
{
//Make sure there is only one instance of this function running
if (isMoving)
{
yield break; ///exit if this is still running
}
isMoving = true;
float counter = 0;
//Get the current position of the object to be moved
Vector3 startPos = fromPosition.position;
while (counter < duration)
{
counter += Time.deltaTime;
fromPosition.position = Vector3.Lerp(startPos, toPosition, counter / duration);
yield return null;
}
isMoving = false;
}
Similar Question: SKAction.scaleXTo
The answer of git1 is good but there is another solution if you do not want to use couritines.
You can use InvokeRepeating to repeatedly trigger a function.
float duration; //duration of movement
float durationTime; //this will be the value used to check if Time.time passed the current duration set
void Start()
{
StartMovement();
}
void StartMovement()
{
InvokeRepeating("MovementFunction", Time.deltaTime, Time.deltaTime); //Time.deltaTime is the time passed between two frames
durationTime = Time.time + duration; //This is how long the invoke will repeat
}
void MovementFunction()
{
if(durationTime > Time.time)
{
//Movement
}
else
{
CancelInvoke("MovementFunction"); //Stop the invoking of this function
return;
}
}
You can use co-routines to do this. To do this, create a function that returns type IEnumerator and include a loop to do what you want:
private IEnumerator foo()
{
while(yourCondition) //for example check if two seconds has passed
{
//move the player on a per frame basis.
yeild return null;
}
}
Then you can call it by using StartCoroutine(foo())
This calls the function every frame but it picks up where it left off last time. So in this example it stops at yield return null on one frame and then starts again on the next: thus it repeats the code in the while loop every frame.
If you want to pause for a certain amount of time then you can use yield return WaitForSeconds(3) to wait for 3 seconds. You can also yield return other co-routines! This means the current routine will pause and run a second coroutine and then pick up again once the second co-routine has finished.
I recommend checking the docs as they do a far superior job of explaining this than I could here

Categories