how to get the the number same for GetNoOfSwitch and switchesLength

The problem is inside the public int GetnoOfSwitch, Using for loop isit correct?

    [SerializeField]
    GameObject[] switches;
    [SerializeField]
    GameObject doorselect;

     int noOfSwitches;
    // Start is called before the first frame update
    private void Start()
    {
        GetNoOfSwitch();
    }
    public int GetNoOfSwitch()
    {
      
        for (int i = 0; i < switches.Length; i++)
        {
           
            if (switches[i].GetComponent<Switch>().isOn == false)
            {
                noOfSwitches = 0;
            }
            else if (switches[i].GetComponent<Switch>().isOn == true)
            {
                noOfSwitches =+1;
            }
           
        }
        return noOfSwitches;
    }
    public void GetDoorState()
    {
        if (GetNoOfSwitch() == switches.Length)
        {
            doorselect.GetComponent<Door>().Dooropen();
        }
        else if (GetNoOfSwitch() != switches.Length)
        {
            doorselect.GetComponent<Door>().Doorclose();
        }
    }
    private void Update()
    {
        GetDoorState();
        Debug.Log(GetNoOfSwitch());
    }

I’m guessing that line 25 is supposed to be += 1 and not =+ 1?
+= 1 increments the number by one.
=+1 sets the number to positive one.

1 Like

if the two switch is On, the number of the will increase until 2 hundred and above

solved

 public int GetNoOfSwitch()
    {
        int x=0;
        for (int i = 0; i <switches.Length; i++)
        {  
            if (switches[i].GetComponent<Switch>().isOn == false)
            {
                noOfSwitches =-1;
                --x;
            }
            else if (switches[i].GetComponent<Switch>().isOn == true)
            {
                noOfSwitches =+1;
                ++x;
            }
        }
        noOfSwitches = x;
        return noOfSwitches;
    }