I’m trying to make a script that when the player moves a certain distance from any gameobject with a certain tag, SetActiveRecursively(false), but only deactivate the object farthest away from the player.
e.g (P is player)
| || | | P | | |
<--
when the player moves to here
| || P| | | | |
set this to false
| ||P | | | | X |
OK, well, if you are trying to keep track of All the objects of a given tag, first you will need an array of all objects with that tag… then you will cycle through the array, checking the distance of each from the player, and setting them accordingly:
var myObjects : List.<GameObject> = new List.<GameObject>();
var maxDistance : float = 20.0;
function Update(){
//GetObjects();
for (var obj in myObjects)
{
if(Vector3.Distance(transform.position,obj.transform.position) > maxDistance && obj.active){
obj.SetActiveRecursively(false);
Debug.Log("Distance is: " + Vector3.Distance(transform.position,obj.transform.position));
}
else if(Vector3.Distance(transform.position,obj.transform.position) <= maxDistance && !obj.active)
obj.SetActiveRecursively(true);
}
}
function GetObjects(){
var tempObjects = GameObject.FindGameObjectsWithTag ("SomeTag");
for(myObj in tempObjects){
if(!myObjects.Contains(myObj))
myObjects.Add(myObj);
}
}
you could uncomment the first line in Update, to make this work, but it is more efficient to only call this relatively expensive function as necessary… so, if you can instead call the function “GetObjects()” only once each time you INSTANTIATE a new object, that will be more efficient… for now, however, go ahead and un-comment the line in Update, if you like…
EDITED: forgot to mention,this script would be attached to the player… using a list gives us the best control, so this should work now I think… The debug should tell you the distance if it turns anything…