Unity Freezing after for loop
Im working on a flappy bird clone to test my skills but my for loop causes the game to crash
The script makes a random position for obstacles if the player is alive and then instantiates them using the random position values with a 4 sec delay from my coroutine
But it freezes on launch please help
CODE:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class ObstacleMaker : MonoBehaviour { public GameObject player; public PlayerController playerScript; public GameObject topObstacle; public GameObject bottomObstacle;
// Start is called before the first frame update
void Start()
{
while (playerScript.isAlive == true)
{
StartCoroutine(loopDelay());
Vector3 topPosition = new Vector3(15.65f, Random.Range(2.5f, 4.48f), 0f);
Instantiate(topObstacle, topPosition, Quaternion.identity);
Vector3 bottomPosition = new Vector3(15.65f, Random.Range(-3.72f, -4.58f), 0f);
Instantiate(bottomObstacle, bottomPosition, Quaternion.identity);
}
}
// Update is called once per frame
void Update()
{
}
IEnumerator loopDelay ()
{
yield return new WaitForSeconds(4);
}
}
Answer by rh_galaxy · Mar 24 at 12:02 AM
Two things.
Start() must be able to finish and exit on its own. If playerScript.isAlive is true when you enter the loop it will never become false because nothing else can set it. You must move this test to Update() which runs every frame.
loopDelay() does not run when you do StartCoroutine. Coroutines are added to a list to be run later. I always find it easier to do timing code directly in Update() myself like this:
private float timer = 0.0f;
void Update()
{
timer += Time.deltaTime;
if(timer >= 4.0f)
{
timer = 0.0f;
if(playerScript.isAlive == true)
{
Vector3 topPosition = new Vector3(15.65f, Random.Range(2.5f, 4.48f), 0f);
Instantiate(topObstacle, topPosition, Quaternion.identity);
Vector3 bottomPosition = new Vector3(15.65f, Random.Range(-3.72f, -4.58f), 0f);
Instantiate(bottomObstacle, bottomPosition, Quaternion.identity);
}
}
}
So if i put your code in place of my current one should it work or is this just a test?
Your answer
Follow this Question
Related Questions
Instantiate Script Not Working 1 Answer
Insantiate Loop Issue 0 Answers
How to make object fall loop? 0 Answers