Access variable from Gameobject found from Vector3

I have a bunch of children objects holding instance variables. What I would like to do is access that instance variable, and find the game object holding that instance variable by searching based on its Vector3 location. Is that possible?

private var rightOne = “”;
private var array : int;

var xPos = 0.0;

var yPos = 0.0;

var zPos = 0.0;

function Start() {
    for (var i = 0; i < transform.childCount; i++) {
           var loc = transform.GetChild(i).transform.position;
           if (loc == Vector3(xPos,yPos,zPos)) {rightOne = rightOne + "," + i.ToString(); break;}
           yield;
    }
array = rightOne.Split(",");

}

Then you could get a array like “0,3,6,8” from the array “array”. Do array to get the values.

They way I’d go about it, is first keep a dynamic list of all children objects of that type in the scene.

You can simply do this in some scene-wide or game-wide object :

public static List<GameObject> myObjects = new List<>();

Next, for every child gameobject that you wish to keep track of:

void Start()
{
   globalObject.myObjects.Add(gameObject);
}

void OnDestroy()
{
  globalObject.myObjects.Remove(gameObject);
}

Next, when you need to find the game object, iterate through all children objects, find their gameObject.transform.position, do a Vector3.Distance from the known Vector3 you are referring to, find the one with shortest distance, and then check if it’s distance is lower than what you need it to be.

GameObject closestOne;
float closestDistanceSoFar = Float.MAX;

for (int i = 0; i < myObjects.Count; i++)
{
   float distance = Vector3.Distance( YourVector3InScene, myObjects*.transform.position);*

if (distance < closestDistanceSoFar)
{
closestDistanceSoFar = distance;
closestOne = myObjects*;*
}
}

//by this point, closestOne is your closest Game Object from the list to the Vector3 location specified, and closestDistanceSoFar is it’s distance to it. Check to see if it’s close enough and then do rest of your logic here.
Then you have found the object you need.