Disable Object and Enable by Distance from Player
Good afternoon everybody, I'm working in a script to enable/disable game objectes when they are far from player to increase the FPS. The script is done and have no errors, but he don't disable/enable the game objects, someone could help me? Thanks a lot.
using UnityEngine; using System.Collections; using UnityStandardAssets.Vehicles.Car;
public class DistanceDisabler : MonoBehaviour {
public GameObject PlayerCar;
public CarController PlayerScript;
public float range = 15;
public GameObject[] ObjectsToDisable;
void Start()
{
PlayerCar = GameObject.FindWithTag("Player");
PlayerScript = PlayerCar.GetComponent<CarController>();
}
void Update()
{
PlayerCar = GameObject.FindWithTag("Player");
PlayerScript = PlayerCar.GetComponent<CarController>();
float distance = Vector3.Distance(PlayerCar.transform.position, transform.position);
{
if (distance >= range)
{
for (int i = 0; i < ObjectsToDisable.Length; i++)
ObjectsToDisable[i].SetActive(false);
}
else
if (distance <= range)
{
for (int i = 0; i < ObjectsToDisable.Length; i++)
ObjectsToDisable[i].SetActive(true);
}
}
}
}
Answer by Alfisti · Jul 22, 2017 at 05:32 PM
I think that I found the problem, but I'm get in other.
I add the "ObjectsToDisable[i]" in line:
float distance = Vector3.Distance(PlayerCar.transform.position, ObjectsToDisable[i].transform.position);
This should work, but the Unity get this error: "Assets/System/Utility/Scripts/DistanceDisabler.cs(26,84): error CS0103: The name `i' does not exist in the current context".
Replacing GameObject[] for one only one Game Object the script works fine, the problem are the multiples objects of GameObject[] that the script don't work. If someone could help thanks!