- Home /
Check if boolean is true on my gameObjects from my array
Hi guys
So i have an array with 5 copies of an gameobject. Each gameObject has also a boolean that becomes true when i land on it for 5 sec with my player. I would like to check that if all the boolean's that are in the array is true then you win the game and change scene
This is the code for the array using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI;
public class Checker : MonoBehaviour
{
public CheckPoint[] CheckPoints = new CheckPoint [6];
void Start()
{
for (int i = 0; i < CheckPoints.Length; ++i)
{
}
}
void captured()
{
for (int i = 0; i < CheckPoints.Length; ++i)
{
if (CheckPoints[i].captured == false)
{
return;
Debug.Log("Checkpoint 1");
}
}
SceneManager.LoadScene(1);
}
}
This is the code for the gameObject
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class CheckPoint : MonoBehaviour { float enterTime = 0; bool entered = false; public bool captured = false;
public void Start()
{
entered = false;
}
private void OnCollisionEnter(Collision collision)
{
enterTime = Time.time;
if (collision.gameObject.tag == "Player")
{
entered = true;
Debug.Log("enterd");
}
}
private void OnTriggerExit(Collider other)
{
enterTime = 0;
entered = false;
}
public void Update()
{
if(entered && Time.time > enterTime + 5)
{
captured = true;
Debug.Log(captured);
}
if(captured == true)
{
}
}
}
Thanks in advance
Answer by VoidVenom · Apr 08, 2021 at 10:01 AM
Since captured
is public, you can just do <gameObject>.GetComponent<CheckPoint>().captured
to access and/or modify it.
Just as a note to keep in mind, though... Unity's implementation of GetComponent
is quite slow so if you'll have lots of CheckPoints or this is something you'll have to do on every frame, for performance you should try to restructure your code so this isn't required.
For example, instead of storing the GameObjects in an array, store their CheckPoint components.
Another possible approach would be to have some sort of function called when a checkpoint is captured that performs whatever is required when all of them are captured.
All of the above are decent approaches to this problem.