I am developing a car game, and I have a script that spawns a section of highway in front and a section of highway behind the player when they enter a trigger, and also places unused sections back into an object pool. The script works well, however, if the player enters the same trigger twice, Unity freezes for several seconds, and then crashes. It also crashes the build. Here is the script:
using UnityEngine;
using System.Collections;
public class EndlessHighway : MonoBehaviour {
public GameObject player;
private GameObject me;
private float fz;
private Transform[] all;
void OnEnable(){
me = this.gameObject.transform.root.gameObject;
all = me.transform.root.GetComponentsInChildren<Transform> ();
for (var i = 0; i < all.Length; i++) {
all *.gameObject.tag = "Highway";*
-
}*
-
fz = me.transform.position.z;*
-
}*
-
void OnTriggerEnter(Collider other){*
-
if (other.transform.root.gameObject == player) {*
-
for(var i = 0; i < all.Length; i ++)*
-
{*
_ all*.gameObject.tag = “Don’t Destroy”;_
_ }_
_ GameObject highwaysToDestroy = GameObject.FindGameObjectsWithTag (“Highway”);_
_ for (var i = 0; i < highwaysToDestroy.Length; i++) {_
_ ObjectPool.instance.PoolObject (highwaysToDestroy );
}
for(var i = 0; i < all.Length; i ++)
{
all.gameObject.tag = “Highway”;
}
GameObject highway1 = ObjectPool.instance.GetObjectForType (“endless highway”, false);
highway1.transform.position = new Vector3 (0, 0, fz + 1000);
highway1.GetComponentInChildren().player = player;
GameObject highway2 = ObjectPool.instance.GetObjectForType (“endless highway”, false);
highway2.transform.position = new Vector3 (0, 0, fz - 1000);
highway2.GetComponentInChildren().player = player;
}
}*_
}