问题
Is it possible add "onClick" function to an Image (a component of a canvas) in Unity ?
var obj = new GameObject();
Image NewImage = obj.AddComponent<Image>();
NewImage.sprite = Resources.Load<Sprite>(a + "/" + obj.name) as Sprite;
obj.SetActive(true);
obj.AddComponent<ClickAction>();
How can I add action for "onClick" event?
回答1:
Supposing that ClickAction
is your script, you could implement the OnClick
functionality in the following way:
using UnityEngine.EventSystems;
public class ClickAction : MonoBehaviour, IPointerClickHandler
{
public void OnPointerClick(PointerEventData eventData)
{
// OnClick code goes here ...
}
}
The namespace UnityEngine.EventSystems
supplies you with the IPointerClickHandler
interface. When your image is clicked, the code inside OnPointerClick
will run.
来源:https://stackoverflow.com/questions/40567303/onclick-event-for-image-in-unity