Search Unity

Control array objects by numbers ?

Discussion in 'Scripting' started by skyLark9, Mar 9, 2019.

  1. skyLark9

    skyLark9

    Joined:
    May 2, 2018
    Posts:
    135
    I'm trying to make my array objects to turn off by using numbers.

    Code (CSharp):
    1.  public GameObject[] weapon_carry_pistol = new GameObject[3];
    2.    public int p1_carry,activeObjects;
    3.  
    4.    // Update is called once per frame
    5.    void Update()
    6.    {
    7.  
    8.    p1_carry =  weapon_carry_pistol[0].GetComponentsInChildren<Button>().Length; // 6 objects
    9.      
    10.    }
    Now I want to use "activeObjects" to turn on/off the array objects. if "activeObjects" = 3, first 3 elements in my array should be active and the rest is deactivated.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    Pretty sure that .GetComponentsInChildren() is not guaranteed to return the objects in any particular order.

    It is better if you hand-drag the specific weapons you want into a button array in the editor, then you can access them by number.
     
    jrumps likes this.
  3. skyLark9

    skyLark9

    Joined:
    May 2, 2018
    Posts:
    135
    I have many weapons, that is why I'm trying to use this method.
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    I don't think that will cause .GetComponentsInChildren() to change.

    Another approach is to get all the buttons, then introspect something about the buttons to decide which one you need, such as the name or the tag or any other MonoBehaviour you might want to attach to it to use for identification.
     
  5. skyLark9

    skyLark9

    Joined:
    May 2, 2018
    Posts:
    135
    You right. I got all button now.
    Code (CSharp):
    1.      for (int i = 0; i < activeObjects; i++)
    2.     {
    3.         weapon_carry_pistol[0].GetComponentsInChildren<Button>()[i].enabled = true;
    4.        
    5.         foreach (Button button in weapon_carry_pistol[0].GetComponentsInChildren<Button>(true) ) {
    6.              button.gameObject.SetActive(true);
    7.         }
    8.  
    9.     }
    The issue now is if I increased "activeObjects" one value, all objects with button active or not show up !!