Moving Platform Code Causes Unity To Crash

I’m writing a script that will move a platform at const speed back and forward between two points. Both points have triggers. This script currently causes unity to be unresponsive and force me to restart computer. This is whats causing it as unchecking its gameobject causes game to run normally. What is causing unity to crash?

using UnityEngine;
using System.Collections;

public class PlatformScript : MonoBehaviour {

	public GameObject pointA;
	public GameObject pointB;

	public float travelSpeed;

	public bool isMoving;

	// Use this for initialization
	void Start () {

	
	// Update is called once per frame
	void Update () {

		while (isMoving) {
		   transform.Translate(Vector3.right * travelSpeed * Time.deltaTime);	
		}
	}

	void OnTriggerEnter(Collider c){
		travelSpeed *= -1;
	}
}

I had the same problem.

I believe it is because your “while” loop will run infinitely which causes unity to crash. This is because you haven’t set a"trigger" to break the loop.

Try to replace “while” with an “if” statement.

If statements don’t cause unity to crash as they are meant to be called only once. The update method is called once per frame, therefore making your if statement run “infinitely”.

This should work :

using UnityEngine;
using System.Collections;
 
public class PlatformScript : MonoBehaviour {
 
    public GameObject pointA;
    public GameObject pointB;
 
    public float travelSpeed;
 
    public bool isMoving;
 
    // Use this for initialization
    void Start () {
 
 
    // Update is called once per frame
    void Update () {
 
       if (isMoving) {
          transform.Translate(Vector3.right * travelSpeed * Time.deltaTime); 
       }
    }
 
    void OnTriggerEnter(Collider c){
       travelSpeed *= -1;
    }
}

Because this is C#, isMoving is initialized with the default false value, but you should still do it yourself (public bool isMoving = false; or isMoving = false; in Start()).
This probably won’t fix the problem though, which means this script doesn’t cause Unity to crash.