Game Development Reference
In-Depth Information
01 //Find objects of matching tag
02 FoundObjects = GameObject.FindGameObjectsWithTag(TagName);
03
04 //Search through all objects and exclude ourselves
05 foreach(GameObject O in FoundObjects)
06 {
07 //If two objects are the same
08 if(O.GetInstanceID() == gameObject.GetInstanceID())
09 continue; //Skip this iteration
10
11 //[...] Do stuff here
12 }
Getting the nearest object
Given an array of GameObjects , perhaps returned from a search, how can you find
the one nearest to you in the scene in terms of linear distance? The following code
sample 3-5 demonstrates how you can find this object using the Vector3.Distance
function to retrieve the shortest distance (in meters) between any two points in
the scene:
//Returns the nearest game object
GameObject GetNearestGameObject(GameObject Source, GameObject[]
DestObjects)
{
//Assign first object
GameObject Nearest = DestObjects[0];
//Shortest distance
float ShortestDistance =
Vector3.Distance(Source.transform.position,
DestObjects[0].transform.position);
//Loop through all objects
foreach(GameObject Obj in DestObjects)
{
//Calculate distance
float Distance = Vector3.Distance(Source.transform.position,
Obj.transform.position);
 
Search WWH ::




Custom Search