Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Setting toggle group on instantiated toggles

Discussion in 'UGUI & TextMesh Pro' started by British_Bandit, Oct 5, 2015.

  1. British_Bandit

    British_Bandit

    Joined:
    Aug 19, 2015
    Posts:
    2
    So I am making an inventory system, my current method involves toggles which will be instantiated as children of the toggle group. My question is how can I set the group of an instantiated toggle in a script?

    Current script:
    Code (CSharp):
    1. public GameObject slot;
    2. public int gap = 2;
    3. public int quantity = 2;
    4. RectTransform slotTransform;
    5.  
    6. void updateDisplay () {
    7.         for (int i=1; i<=quantity; i++) {
    8.             slotTransform = slot.GetComponent<RectTransform>();
    9.             slotTransform.localPosition = new Vector3(0,-(i-1)*(2+slotTransform.sizeDelta.y));
    10.             Instantiate (slot).transform.SetParent (transform,false);
    11.         }
    12.     }
     
    Last edited: Oct 5, 2015
  2. karl_jones

    karl_jones

    Unity Technologies

    Joined:
    May 5, 2015
    Posts:
    7,852
    So slotTransform is a prefab with a Toggle?
    Call GetComponent<Toggle> on slotTransform and set the group using Toggle.group.

    Code (csharp):
    1. var toggle = slotTransform.GetComponent<Toggle>();
    2. toggle.group = GetComponent<ToggleGroup>(); // Guessing you the group is on the same object
     
    British_Bandit likes this.
  3. British_Bandit

    British_Bandit

    Joined:
    Aug 19, 2015
    Posts:
    2
    Tried this and it initially failed. I then realised that I never added UnityEngine.UI to the uses clause.
    Thanks for the help anyway!
     
    karl_jones likes this.