Set UIButton.onClick from Parent UISprite

Hello

My UISprite contains a UIButton (the button is a child of the sprite). The sprite has a method that should be called when the child button is clicked.

How can the parent UISprite set the UIButtons onClick property/event?

public class MessageBox : UISprite{

     private UIButton okBt = null;

     public void Awake() {
           okBt = transform.FindChild("ButtonOK").GetComponent<UIButton>();
           okBt.onClick = onOkClick;  // compiler error occurs here
     }

     public void onOkClick() {
          hide ();
     }
}

1 Answer

1

If you want to do it in a C# way, you can use delegates and events. Here is an example :

public class MessageBox : UISprite {
	
	private UIButton okBt = null;
	
	public void Awake() {
		okBt = transform.FindChild("ButtonOK").GetComponent<UIButton>();
		okBt.OnClick += onOkClick;
	}
	
	public void onOkClick() {
		hide ();
	}
}

public class UIButton : UISprite {

	public delegate void OnClickDelegate();

	[HideInInspector]
	public event OnClickDelegate OnClick;

	void OnMouseDown() {
		if(OnClick != null) {
			OnClick();
		}
	}
}

If you would like to read more about events and delegates, please follow this link : Events Tutorial.