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.
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...
}
Works perfectly! Big thanks!