How To Set Active/Deactivate A GameObject after calculating it's Distance from the player..?

To reduce the force on CPU and make my game run smooth i created a script and attached it to every object which i wanted to be deactivated once the players moves away and activated again once the player comes near, this was the script.

private var Player : Transform;

function Start () {

}

function Update () {
Player = GameObject.FindGameObjectWithTag("Player").transform;

if(Vector3.Distance(Player.position, transform.position) > 20)
{
	gameObject.SetActive(false);
}

if(Vector3.Distance(Player.position, transform.position) < 20)
{
	gameObject.SetActive(true);
}

}

soon i founded that it was not a good idea as a deactivated object will not be able to activate itself again,

so is there, any way to make this script work? or am i missing something? i know there’s a solotion that i could attach those objects to a parent empty object and attach this script to the parent object and make it run checking every child’s pos. but i cant due to some reasons hence i need another solution…!

any help is appreciated…

This type of optimization is performed by special objects called managers. They have scripts to control when and what activates and deactivates. There is no common way of doing them due to how overall game-design can change the possibility of using various optimization techniques, but in general it something like this:

public class DistanceCullingManager : MonoBehaviour{
public List<GameObject> trackables = new List<GameObject>();

void Update(){
foreach(GameObject go in trackables){
//Disabling/Enabling code there
}
}
}

Take note this is the worst way of doing it, but I hope this will show the general idea.

Most optimization to this include per-frame enumeration stepping, listing only disabled objects(which are registered when disabled) and so on. Be creative :wink:

As the doc says: Unity - Scripting API: GameObject.SetActive

Any scripts that you have attached to the GameObject will no longer have Update() called, for example.

So if you want to do this, consider storing all of the gameobjects that you want to check in a array, and have a script atached to the player for example, which could check every item of the array regarding their position and the enable state. If you want some help about this, just ask