- Home /
My unity freezes as i press the play button.
My unity freezes as i press the play button. The code is not in an infinite loop either. I'm just a beginner. Please help me out. As soon as i remove the code from the object it plays perfectly. When i apply it to the object it freezes when i press the play button.,Unity just freezes when I press the play button. Just a small code but i dont think there is an infinite loop. This is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Rock : MonoBehaviour {
[SerializeField] Vector3 topPosition;
[SerializeField] Vector3 bottomPosotion;
// Use this for initialization
void Start () {
StartCoroutine(move(bottomPosotion));
}
IEnumerator move(Vector3 target)
{
while (Mathf.Abs((target - transform.localPosition).y) > 0.20f) ;
{
Vector3 direction = target.y == topPosition.y ? Vector3.up : Vector3.down;
transform.localPosition += direction * 4 * Time.deltaTime;
yield return null;
}
print("Reached the Target");
yield return new WaitForSeconds(0.5f);
Vector3 newTarget = target.y == topPosition.y ? bottomPosotion : topPosition;
StartCoroutine(move(newTarget));
}
},
Answer by bobisgod234 · Jun 05, 2018 at 05:32 AM
Remove the semicolon that is on the end of the while statement:
while (Mathf.Abs((target - transform.localPosition).y) > 0.20f) ; // <-- semicolon here is bad
becomes
while (Mathf.Abs((target - transform.localPosition).y) > 0.20f)
Answer by MuffinMan64 · Jun 05, 2018 at 06:54 AM
Try commenting out StartCoroutine(move(newTarget));
at the end. That looks like an infinite loop, because it's calling itself.
If that doesn't work, the while loop may not be working as expected. For example, if the while loop condition is never true, that could be an infinite loop with the StartCoroutine(move(newTarget));
at the end.
To test this, you could have Debug.Log(Mathf.Abs((target - transform.localPosition).y) > 0.20f);
before the while loop.
And Debug.Log(newTarget);
before calling the StartCoroutine(move(newTarget));
Play around with the Debug.Log() and commenting things out, and let us know your findings!