Search Unity

Trouble with buttons

Discussion in 'Scripting' started by IK, Dec 5, 2016.

  1. IK

    IK

    Joined:
    Oct 29, 2012
    Posts:
    34
    Greetings,

    I am having an issue with add a onclick listener to a dynamic button. Whatever I try it doesn't appear to be adding as viewed from the editor. Here is what I have:

    Code (CSharp):
    1. private Button getButton(int i)
    2.     {
    3.         Button buttonPanel = (Button)Instantiate(buttonPF, transform.position, transform.rotation);
    4.         buttonPanel.name = ("Button");
    5.         Image panelImage = buttonPanel.image;
    6.         panelImage.sprite = GameConstants.basicBackground;
    7.         panelImage.type = Image.Type.Sliced;
    8.         panelImage.color = new Color(0.4f, 0.4f, 0.4f, 1.0f);
    9.  
    10.         buttonPanel.onClick.RemoveAllListeners();
    11.         buttonPanel.onClick.AddListener(delegate { doThing(i); });
    12.  
    13.         GameObject buttonLabel = new GameObject("Button Text");
    14.         Text buttonText = buttonLabel.AddComponent<Text>();
    15.         buttonLabel.transform.SetParent(buttonPanel.transform);
    16.         buttonText.font = GameConstants.defaultFont;
    17.         buttonText.alignment = TextAnchor.MiddleCenter;
    18.         buttonText.fontSize = 20;
    19.         buttonText.text = getButtonText(i);
    20.         buttonText.rectTransform.sizeDelta = new Vector2((sideBarWidth / 4) - 10.0f, 35.0f);
    21.         buttonText.rectTransform.localPosition = new Vector2(0.0f,0.0f);
    22.  
    23.         panelImage.rectTransform.sizeDelta = new Vector2((sideBarWidth / 4) - 00.0f, 40.0f);
    24.  
    25.         if (i == 3)
    26.         {
    27.             panelImage.color = new Color(0.8f, 0.0f, 0.0f, 1.0f); ;
    28.         }
    29.  
    30.         return buttonPanel;
    31.     }
    32.  
    33.     public void doThing(int i)
    34.     {
    35.         Debug.Log("Hit!");
    36.     }
    Thanks for your time.
     
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    listeners added through code don't appear in the inspector.
     
  3. IK

    IK

    Joined:
    Oct 29, 2012
    Posts:
    34
    Is there anyway to check if they are added correctly? My buttons still don't do anything and I was thinking that maybe I added them wrong but maybe my button just isn't working? Thanks!