Whenever I use Coroutines there is always a risk of it completely freezing my game upon pressing play.
For example I’m making a little game where both player and enemies have Coroutines to shoot with delay, rather than constantly. Everything works fine but when I add while() to something the game freezes upon starting it.
Player Coroutine…
Starts in the PlayerScript when GetMouseButtonDown(0) and ends when GetMouseButtonUp(0)
IEnumerator FireContinuously()
{
while (true)
{
GameObject playerProjectile = Instantiate(projectile, transform.position, Quaternion.identity) as GameObject;
playerProjectile.GetComponent<Rigidbody2D>().velocity = new Vector2(direction.x * projectileSpeed, direction.y * projectileSpeed);
yield return new WaitForSeconds(firingSpeed);
}
}
Enemy Coroutine…
Starts in the EnemyGun Start() and runs constantly
IEnumerator EnemyShootGun()
{
while (true)
{
yield return new WaitForSeconds(UnityEngine.Random.Range(firingSpeed, firingSpeed + firingSpeed));
GameObject enemyProjectile = Instantiate(projectile, transform.position, Quaternion.identity) as GameObject;
enemyProjectile.GetComponent<Rigidbody2D>().velocity = new Vector2(direction.x * projectileSpeed, direction.y * projectileSpeed);
}
}
Code causing my game to freeze…
Public method in the EnemyScript Start() that moves the enemy to certain waypoints
public void EnterArena()
{
int targetPosition = 0;
transform.position = wayPoints[targetPosition].transform.position;
while(targetPosition < wayPoints.Count)
{
Debug.Log("testing");
}
}
I would really appreciate if someone knew what is going on as my other games were also plagued by Coroutines freezing after implementing while() somewhere.
Additional info:
Both player and enemies are made of parent object that has two children
Parent - has script (EnemyScript / PlayerScript) controlling movement and behavior
Child(hull) - just sprite
Child(gun) - gun sprite with code to control its rotation and shooting (EnemyGun / PlayerGun)