- Home /
Filter an array using booleans.
I have a list of checkpoints (tag = checkpoint) of which each has an "ObjectiveControl" script with a bool "playerControl". How do I make a list of all the checkpoints where "playerControl = true"?
I figured I'd start with GameObject[] checkpoint = GameObject.FindGameObjectsWithTag("checkpoint"); for (int i = 1; i < checkpoint.Length; i++)
but am not sure how to proceed after that.
Answer by SkaredCreations · Oct 11, 2018 at 05:52 PM
Here is:
List<ObjectiveControl> foundCheckpoints = new List<ObjectiveControl>();
GameObject[] checkpoint = GameObject.FindGameObjectsWithTag("checkpoint");
foreach (GameObject obj in checkpoint)
{
ObjectiveControl comp = obj.GetComponent<ObjectiveControl>();
if (comp != null && comp.playerControl)
{
foundCheckpoints.Add(comp);
}
}
// Now you can do: foreach (ObjectiveControl comp in foundCheckpoints) { /* do stuff */ }
PS: if you use a for() loop instead of foreach() then remember that arrays and lists start with index 0 and not 1:
for (int i = 0; i < checkpoint.Length; ++i)
{
// do stuff...
}
What if I want to repopulate the list a couple of times? (The intent is to create a list of checkpoints to which the game object has to to go) I did as you suggested in Start - and it was perfect. But when I put it in update it only worked once. So the game object found the closest checkpoint from the original list and got there. Then it repopulated the list, found the next closest checkpoint and went to it. But after that it did not repopulate the list. Navigation(path[currentCheckpoint].position); if (Vector3.Distance(this.transform.position, path[currentCheckpoint].position) < 1) { closestCheckpoint = path[currentCheckpoint].GetComponent(); if (closestCheckpoint.player2Control)
{
List<Transform> path = new List<Transform>();
GameObject[] checkpoint = GameObject.FindGameObjectsWithTag("checkpoint");
foreach (GameObject go in checkpoint)
{
ObjectiveControl comp = go.GetComponent<ObjectiveControl>();
if (comp != null && comp.player1Control)
{
path.Add(comp.transform);
Debug.Log(path);
currentCheckpoint = FindClosestCheckpoint();
}
}
}
Your answer
Follow this Question
Related Questions
Add GameObject to an Array. 1 Answer
Why am I getting an error CS0103? 1 Answer
Change an objects Array position dynamiclly in a match 3 game 0 Answers
Arrays don't show up on inspector 1 Answer
How to arrange list 3 Answers