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. Dismiss Notice

Passing a method through to a button's OnClick() listener?

Discussion in 'Scripting' started by Eoghan, Dec 26, 2014.

  1. Eoghan

    Eoghan

    Joined:
    Jun 6, 2013
    Posts:
    80
    Hey guys, I'm hoping someone on here might have some experience with Unity2D/4.6 UI elements. I'm building a system that procedurally generates random items, and loads them into a storefront system. I've got a barebones prefab which the script is filling - stats, image, etc etc. The problem is in filling the method to be called via the button's OnClick method.

    Currently I've got the following script on it's parent container; note that the method being passed through is just a Debug.Log call, to see if the button is actually working.

    Code (CSharp):
    1.     Transform purchaseButton = newItem.transform.FindChild("Purchase");
    2.         if (purchaseButton != null) {
    3.             Debug.Log("found button");
    4.             UnityEngine.Events.UnityAction action1 = () => { Debug.Log ("Got a button click"); };
    5.             purchaseButton.GetComponent<Button>().onClick.AddListener(action1);
    6.  
    7.             Transform buttonText = purchaseButton.transform.FindChild("Text");
    8.             buttonText.GetComponent<Text>().text = "Purchase " + itemNames;
    9.         }

    Altering the buttonText works fine and as expected; and obviously, I've no problem in finding the button object via the script. There's no compile-time, or run-time errors to speak of. However, try as I may, I can't pass through the new action into the onClick listener.

    Can anyone lend me a hand, or some advice on this? I'd very much appreciate it :)
     
  2. ViperCode_

    ViperCode_

    Joined:
    Apr 11, 2011
    Posts:
    19
    What is the code on the button?
     
  3. Eoghan

    Eoghan

    Joined:
    Jun 6, 2013
    Posts:
    80
    There is no code attached to the button; it's set up with a blank onClick listener, and I'm looking to pass through the relevant code method via a parent object.

    I've gotton event listener updating working fine on a script that's actually attached to the button itself; but if accessed from an external class, it seems to just.. not exist. No compile/run-time errors, debug.log shows that the correct method is being accessed.. but it just refuses to actually update the onClick method.