- Home /
Please help !! Custom Button Event Not responding !!
Here is my Code. The Function doSomething() wont execute on button click. Can you tell me what i am doing wrong. Thanks
using UnityEngine; using System.Collections; using UnityEngine.UI;
public class Arrow : MonoBehaviour {
public GameObject myarrow;
private Button myButton;
void Start () {
myarrow = GameObject.Find("Arrow_Sprite");
myarrow.AddComponent<Button> ();
// myarrow.GetComponent<Button> ().enabled = true;
// myButton.GetComponent<GameObject> ().gameObject = myarrow.gameObject;
// myButton = myarrow.GetComponent<UnityEngine.UI.Button> ();
myarrow.GetComponent<Button>().onClick.AddListener (delegate {
doSomething();
});
myarrow.GetComponent<Button>().enabled = true;
}
public void doSomething()
{
myarrow.transform.position = new Vector2 (5, 2);
}
// Update is called once per frame
void Update () {
}
}
Answer by aditya · Aug 17, 2016 at 01:37 PM
Try this ...
public GameObject myarrow;
void Start () {
myarrow = GameObject.Find("Arrow_Sprite");
myarrow.AddComponent<RectTransform>();
myarrow.AddComponent<Button> ();
myarrow.GetComponent<Button>().onClick.RemoveAllListeners();
myarrow.GetComponent<Button>().onClick.AddListener (doSomething);
myarrow.GetComponent<Button>().enabled = true;
}
public void doSomething()
{
Vector3 newPos = new Vector3(5f, 2f, 0f);
newPos.z = myarrow.transform.position.z;
myarrow.transform.position = newPos;
}
Its doing nothing. Just so you know.
Its a 2d game
I have not made an instance of the arrow on the scene.
How do i link this arrow in the inspector. It is a prefab. I am trying to instantiate it via code alone. It has to be a sprite instantiated as a button via code.
Okay ... if you are instantiating UI elements at runtime then unity manual is a must see Creating UI Element at Runtime ... and paste my above code in the same script which is instantiating your button ... the change the first line of my code to public Button myarrow;
... then simply assign this newly instantiated button to myarrow
Your answer
![](https://koobas.hobune.stream/wayback/20220612090919im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Buttons not working properly. 0 Answers
UI button in Panel not clickable 2 Answers
Custom Android Textfield and Button 0 Answers
Use Singleton Prefab in Button's onClick editor field 0 Answers