- Home /
Endless Highway script CRASHES Unity!?
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 [i].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[i].gameObject.tag = "Don't Destroy";
}
GameObject[] highwaysToDestroy = GameObject.FindGameObjectsWithTag ("Highway");
for (var i = 0; i < highwaysToDestroy.Length; i++) {
ObjectPool.instance.PoolObject (highwaysToDestroy [i]);
}
for(var i = 0; i < all.Length; i ++)
{
all[i].gameObject.tag = "Highway";
}
GameObject highway1 = ObjectPool.instance.GetObjectForType ("endless highway", false);
highway1.transform.position = new Vector3 (0, 0, fz + 1000);
highway1.GetComponentInChildren<EndlessHighway>().player = player;
GameObject highway2 = ObjectPool.instance.GetObjectForType ("endless highway", false);
highway2.transform.position = new Vector3 (0, 0, fz - 1000);
highway2.GetComponentInChildren<EndlessHighway>().player = player;
}
}
}
Have you tried debugging the problem? Which line of your script does the game crash on? And what is the state of the variables when it crashes? Do you get any error messages/logs?
There were no error messages or logs. However, I did find a similar question that stated that unity crashes when assigning tags in certain situations (specifically loops), so it could be related to that.
Answer by Xarbrough · Jun 24, 2015 at 09:33 AM
Usually, when something also crashes the built, it's not a bug in the editor. I would guess it runs in some kind of endless loop. Have you tried removing all statements from within your loops and replacing them with print? Comment out most of the logic and enable it bit by bit to narrow down where it crashes and if all loops are being terminated.
It turns out that it was getting stuck in an endless loop. I removed the for loop and changed only the tag of the transform root, while leaving its children untagged.