Changing isTrigger value of all objects in an array

Hey, I’m making a game for class where you go through a first person maze with various types of walls that do different things depending how you interact with them,

I have all of them finished, except for one, which is solid when you look at it, but not when you aren’t. Like a Boo from Mario for example. However, I want this to apply to ALL types of this wall, across the board. A visualization here:

So I gave these walls a tag: BooWall, and passed in all objects with this tag on my PlayerScript where I am keeping the logic for interactions with all other walls:

    FirstPersonController controller;

    public GameObject[] BooWalls;

    void Start () {
        if (BooWalls == null)
            BooWalls = GameObject.FindGameObjectsWithTag("BooWall");
        controller = GetComponent<FirstPersonController> ();

    }

And then I get down to the raycast:

    void Update () {
        checkCollision ();
}
void checkCollision(){
        RaycastHit hit;
        if (Physics.Raycast(transform.position, transform.forward, out hit, 10f, -1))
        {
       
   
            if (hit.collider.gameObject.tag == "BooWall"){
                Debug.Log ("Looking at a boowall");
                foreach (GameObject boowall in BooWalls){
                    Debug.Log("Turning Walls Solid");
                    boowall.GetComponent<BoxCollider>().isTrigger = false;
               
                }
            }
           
        }
        else
        {
            foreach (GameObject boowall in BooWalls){
                boowall.GetComponent<BoxCollider>().isTrigger = true;
                Debug.Log ("turning walls open");
            }


            }
    }

Except the foreach loop is doing nothing. The “Looking at boowall”, is calling when I’m looking at the wall, but the “Turning Walls Solid”, and “turning walls open” are not being called. Any advice?

This begs to be done via static variables. (A static variable is a variable that’s attached to the class as a whole, instead of a specific instance of it. Stuff like Camera.main, for example.) The only challenge is, if we make it a simple bool, how do we set it to false? The quickest and easiest solution: Make it a float, representing the time a BooWall was last “seen” by the player. If that time is now, they’re all hidden.

Attach a BooWall component to each of your BooWalls, with code like this on it:

public static float timeLastLookedAt = -1f;
void LateUpdate() {
myBoxCollider.enabled = Time.time <= timeLastLookedAt;
}
//in checkCollision:
if (Physics.Raycast(transform.position, transform.forward, out hit, 10f, -1))
        {
BooWall.timeLastLookedAt = Time.time;
}

And it’s that simple!

1 Like

It works! Thank you so much!

1 Like