On Click paramaters disappear from button prefab?

I’m trying to learn how to use the new 4.6 GUI. I made a canvas with a button in the inspector. I added a script to another GameObject with a method to do something when the button was press. I added the GameObject along with the script and method information to the buttons OnClick area. Everything worked fine. Ran the program, pressed the button, things happened, no problems.

Then I tried to take that canvas and make it a prefab. The problem is when I Instantiate the canvas prefab (with the button attached) the OnClick info is no longer there and the button now does nothing. I have scrapped it and started from scratch several times but for the life of me I cannot figure out what the problem is. I was hoping someone here could enlighten me?


Finally figured out a way to do this. Hope someone finds this answer useful.

To be able to add a button click to an instantiated prefab.

  1. Add the script directly to your prefab.
  2. Drag the attached script from your prefab to the OnButton click event of the same prefab.
  3. Assign the function that you wish to be called using the Onbutton click handler.

Now, Apply the changes to the prefab and play the scene. The instantiated prefabs should have your onClick info attached.

You can ask in the Beta group, where our developers could help.

@PigChop, here is a way that you can instantiate a button from a prefab and attach any method that you wish. By setting this up as shown the parameter “value” will remain associated with the button that it is assigned to. So if you have “value = 1” when you create one button and “value = 2” when you create a second button then each button will retain that value. When you click on the button the delegate “myButtonDelegate” will receive the value that was assigned to it at instantiation. But they are fixed values and will always be what was assigned.

public void CreateMyButton()
                int value = 1;
                GameObject tButton = (GameObject)Instantiate(ButtonPrefab);
                Button buttonCtrl = tButton.GetComponent<Button>();
                buttonCtrl.onClick.AddListener(() => myButtonDelegate( value ));

void myButtonDelegate(int myValue)
                // myValue will be equal to 1 here

five years on and @architrathi answer still works! thanks!

I was struggling with the exact same problem too. You can also make a prefab out of the GameObject your script is attached to and this allows the instantiated button to find the script. Prefabs everywhere …

Please comment if this solution has caveats.