Is it possible to set up an array or data structure of some kind where the keys are vector3’s?
You can’t use Vector3 as keys directly, since the hash will be generated from the object itself, not it’s contents, which is what you want.
I’ve made an extension that returns a unique int from a vector. I’m my case I only need to know it’s discrete integer values, and I assume they will never be larger than 1000. You can change it to suit your needs if needed, but the gist will be the same.
//=========================================================================
// Rounds coordinates to integers, and returns an int that can easily be hashed and used as a key
// Assumes coordinates will never be greater than 1000 in any direction
public static int HashableInt(this Vector3 vector)
{
int x = Mathf.RoundToInt(vector.x);
int y = Mathf.RoundToInt(vector.y);
int z = Mathf.RoundToInt(vector.z);
return x * 1000 + z + y * 1000000;
}
You could use a hashtable or a dictionary:
var objectArray : GameObject [];
/* example using a hashtable */
var vectorHash : Hashtable = new Hashtable();
/* create hashtable to lookup gameobjects by their position */
for ( var thisObject : GameObject in objectArray ) {
var theVect : Vector3 = thisObject.transorm.position;
vectorHash[theVect] = thisObject;
}
/* example using a dictionary */
var vectorTable : Dictionary.<Vector3, GameObject> =
new Dictionary.<Vector3, GameObject> ();
for ( var thisObject : GameObject in objectArray ) {
var theVect : Vector3 = thisObject.transorm.position;
vectorTable[theVect] = thisObject;
}