How could I optimize these lines of code?

When I was writing this code, I knew it wouldn’t be good performance wise due to the expensiveness of the statements in it, but I’m not really sure how I could optimize it while still maintaining the same functions. How it works is whenever the player steps on a blue switch, the blue walls slide open, while the red switches and red walls close. Then the same goes for whenever I step on a red switch, except the blue switches and walls close. In the Start() function, I define thisSwitch as whatever objects have the tag BlueSwitch or Red Switch, then I define otherSwitch as the objects with the tag I didn’t use for thisSwitch.

function OnTriggerEnter (col : Collider)
{
    if(col.gameObject.name == "player1" && player1 == true || col.gameObject.name == "player2" && player2 == true){
        Down();
    }

}

function Down () {
    for (i=0; i < thisSwitch.length; i++)
    {
    if (thisSwitch[i].GetComponent("Animator").GetBool("pressed") != null){
        thisSwitch[i].GetComponent("Animator").SetBool("pressed", true);
    }
    if (thisSwitch[i].GetComponent("Animator").GetBool("open") != null){
        thisSwitch[i].GetComponent("Animator").SetBool("open", true);
    }
    }
   
    for (i=0; i < otherSwitch.length; i++)
    {
    if (otherSwitch[i].GetComponent("Animator").GetBool("pressed") != null){
        otherSwitch[i].GetComponent("Animator").SetBool("pressed", false);
    }
    if (otherSwitch[i].GetComponent("Animator").GetBool("open") != null){
        otherSwitch[i].GetComponent("Animator").SetBool("open", false);
    }
    }

I’m not sure how I could optimize this (the performance drops only happen for a second though since the Down() function only happens OnTriggerEnter). Any help is appreciated :slight_smile: Thanks.

This helped the performance a lot. I changed the bool in the actual switches from “pressed” to “open” to avoid using the “!= null” lines of code so that I could use the same statements for the walls and the switches. This is what the code looks like now:

function OnTriggerEnter (col : Collider)
{
    if(col.gameObject.name == "player1" && player1 == true || col.gameObject.name == "player2" && player2 == true){
        Down();
    }

}

function Down () {
    for (i=0; i < thisSwitch.length; i++)
    {
        thisSwitch[i].GetComponent("Animator").SetBool("open", true);
    }
   
    for (i=0; i < otherSwitch.length; i++)
    {
        otherSwitch[i].GetComponent("Animator").SetBool("open", false);
    }
}

You could cache the GetComponent calls.
Instead of an array of GameObjects have an array of Animators.

Feeling brave, why not decouple the system and use UnityEvents.

1 Like