I have walls in my scene, each wall has a set of waypoints in it with the tag waypoint
what i want to know is how to put the child way points into an array
code so far
private GameObject[] waypoints;//<---- need to get the children with tag"waypoint" in here
private GameObject[] walls;
void Start{
walls = GameObject.FindGameObjectsWithTag ("wall");
}
void Update(){
foreach(GameObject wall in walls) {
foreach (Transform Child in wall.transform) {
//stuck here, need to get all the children with the tag "waypoint" into the game object array called waypoints
}
}
}
Try this, modify it to suite your code:
List waypoints=new List();
private GameObject[] walls;
void Update(){
foreach(GameObject wall in walls) {
Transform[] childrenOnthisWall = gameObject.GetComponentsInChildren();
foreach (Transform child in childrenOnthisWall){
if (child.tag == "waypoint"){
waypoints.Add(child.gameObject);
}
}
}
}
I think your logic is wrong: if you search for the farthest waypoint each Update, the AI may enter an infinite loop. When needed, you should use FarthestWaypoint(NearestWall()) to find the desired waypoint:
private GameObject[] walls;
void Start{
walls = GameObject.FindGameObjectsWithTag ("wall");
}
// to find the desired waypoint, use this:
...
GameObject waypoint = FarthestWaypoint(NearestWall());
...
// these are the functions:
GameObject NearestWall(){
float distance = Mathf.Infinity;
GameObject nearest;
foreach (GameObject wall in walls){
// get its squared distance to save a few CPU cycles...
float dist2 = (wall.transform.position - transform.position).sqrMagnitude;
if (dist2 < distance){ // if closer than current min distance...
nearest = wall; // this is the new nearest wall
distance = dist2;
}
}
return nearest;
}
GameObject FarthestWaypoint(GameObject wall){
float distance = -1;
GameObject farthest;
foreach (Transform child in wall.transform){
if (child.CompareTag("waypoint")){ // if found a waypoint...
// get its squared distance to save a few CPU cycles...
float dist2 = (child.position - transform.position).sqrMagnitude;
if (dist2 > distance){ // if farther than current max distance...
farthest = child.gameObject; // this is the new farthest object
distance = dist2;
}
}
}
return farthest;
}