2016-11-12 56 views
4

是否可以在Unity中爲圖像(畫布的一個組件)添加「onClick」函數?onClick事件在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>(); 

如何爲「onClick」事件添加動作?

回答

11

我想ClickAction是你的腳本。它可能是這個樣子:

using UnityEngine.EventSystems; 

public class ClickAction : MonoBehaviour, IPointerClickHandler 
{ 
    public void OnPointerClick(PointerEventData eventData) 
    { 
     // OnClick code goes here ... 
    } 
} 

命名空間UnityEngine.EventSystems提供您與IPointerClickHandler接口。點擊圖片後,OnPointerClick中的代碼將會運行。

+0

工作正常:)謝謝! – Quicki

+0

@Quicki歡迎您!如果您有任何進一步的問題,請隨時詢問他們。 :) –