- Home /
How to fix this script?
I'm using this script to dynamicaly enable/disable terrain object based on player position. It works on demo scene but in my game scene there are literally hundreds of terrain objects that I need to keep disabled when working in editor due of performance drop. But the script isn't working properly if those terrains aren't enabled before entering playmode.
Unfortunately I can't enable all the terrains - it freezes and crashes the editor.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HideTiles : MonoBehaviour {
[SerializeField]
private string tileTag;
[SerializeField]
private Vector3 tileSize;
[SerializeField]
private int maxDistance;
private GameObject[] tiles;
void Start () {
this.tiles = GameObject.FindGameObjectsWithTag (tileTag);
DeactivateDistantTiles ();
}
void DeactivateDistantTiles() {
Vector3 playerPosition = this.gameObject.transform.position;
foreach (GameObject tile in tiles) {
Vector3 tilePosition = tile.gameObject.transform.position + (tileSize / 2f);
float xDistance = Mathf.Abs(tilePosition.x - playerPosition.x);
float zDistance = Mathf.Abs(tilePosition.z - playerPosition.z);
if (xDistance + zDistance > maxDistance) {
tile.SetActive (false);
} else {
tile.SetActive (true);
}
}
}
void Update () {
DeactivateDistantTiles ();
}
}
This might have something to do with the fact that you often can't find disabled game objects using GameObject.Find() and its related methods. $$anonymous$$aybe try using the Transform.FindObjectsOfType() method to identify the disabled tiles?
Answer by AlirezaSH2004 · May 18, 2020 at 06:27 PM
Hello there. I think using “Try & Catch” can be firstly showing you the exception and also handling the unexpected errors and exceptions. Can this help?