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()
Related
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);
}
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
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I am trying to implement it so that you can shoot 2 times per second. I am doing this by shooting, and then delaying the gun controlling script for 0.5 seconds, but it's not working. I am trying to use the WaitForSeconds function.
I expect that when I click, a shoot immediately happens, and for the next 0.5 seconds clicking will have no effect while the rest of the game happens normally, and after that time, clicking once will shoot again, causing another delay and so on.
Instead, I can shoot over and over with nothing slowing it down.
Here's my script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GunController : MonoBehaviour
{
public Transform firePoint;
public GameObject bulletPrefab;
public string gunType;
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
switch (gunType)
{
case "pistol":
StartCoroutine(ShootThenDelay(0.5f));
break;
}
}
}
IEnumerator ShootThenDelay(float seconds)
{
Shoot();
yield return new WaitForSeconds(seconds);
}
void Shoot()
{
GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
}
}
A Coroutine does not delay the method that is starting it (with one exception - see below) .. otherwise your entire app would be frozen.
You could though simply add a flag like e.g.
bool canShoot = true;
IEnumerator ShootThenDelay(float seconds)
{
canShoot = false;
Shoot();
yield return new WaitForSeconds(seconds);
canShoot = true;
}
and then check for
if (canShoot && Input.GetMouseButtonDown(0))
Alternatively in your case you actually could directly wait until the routine is finished using
// Yes! If you make Start return IEnumerator then Unity
// automatically runs it as a Coroutine
private IEnumerator Start()
{
// Looks dangerous but is totally fine for a Coroutine as long as you yield inside
while(true)
{
if (Input.GetMouseButtonDown(0))
{
switch (gunType)
{
case "pistol":
// "Runs" the shoot routine and waits until it finished
// This way a yield at the end actually has an effect
yield return ShootThenDelay(0.5f));
break;
default:
// Note: This is very important! Make sure all paths within the while yield at least for one frame!
yield return null;
break;
}
}
else
{
// Note: This is very important! Make sure all paths within the while yield at least for one frame!
yield return null;
}
}
}
IEnumerator ShootThenDelay(float seconds)
{
Shoot();
yield return new WaitForSeconds(seconds);
}
That is because after waiting for 0.5 seconds, the coroutine returns to the point in code where execution was halted, in your example it returns to the line that goes after:
yield return new WaitForSeconds(seconds);
However, there is nothing, so nothing happens. If you do something like this:
IEnumerator ShootThenDelay(float seconds)
{
Shoot();
yield return new WaitForSeconds(seconds);
Shoot();
}
bullet must be shot twice with the delay of 0.5 seconds.
I do recommend you checking the documentation next time :)
https://docs.unity3d.com/ScriptReference/WaitForSeconds.html
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
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