# 互動 **點擊物件觸發互動(跳出圖片or動畫)** Method 1 : 將要顯示的圖片在點擊後加入到原來的object中,再次點擊即關閉。 照片加入的地方:Create >> UI >> Image ![](https://i.imgur.com/7YWzpLR.png) ![](https://i.imgur.com/hI1vmQ5.png) https://forum.unity.com/threads/making-an-image-appear-when-an-object-is-clicked.407575/ Method 2 : 將所要click後顯示的圖片(不確定動畫是否可)做成gameobject 在所要觸發的object的script中打入你要呈現的畫面 ![](https://i.imgur.com/l8pEgxM.png) 這邊是將click一個圓球之後,可以控制燈的開關 →改成將所要的東西隱藏or顯示 Ex GameObject cat; cat.SetActive(false); //將cat隱藏(改寫成if else 隱藏時就開,出現時就關) https://www.youtube.com/watch?v=DrR0soJDCUo *如果說要變成動畫我就不確定ㄌ... 但我有找了其他相關的* **鼠標滑過UI物體時觸發動畫** ex.游標放到筆記本上,出現會動的字體(動畫) 1. 給object加入box collider(打勾) 再寫入觸發內容(且碰撞器不能是trigger) void OnMouseDown(){寫入要觸發的內容 ex. 播放動畫:animation.play("動畫名") 移動物體:transform.translate(0,0,1);} * OnMouseEnter()[鼠標進入],OnMouseExit()[鼠標離開]實現鼠標懸停時各種效果(UI+3D物體) * OnMouseOver() v.s. OnMouseEnter() 當鼠標在該物體上collider內時 每幀調用1次.v.s.在鼠標進入時只調用1次 2. 給需要有動畫的物體添加程式碼 ``` public class OnBtnEnter : MonoBehaviour, IPointerEnterHandler,IPointerExitHandler { //鼠標進入按鈕(object)觸發音效和動畫 public void OnPointerEnter(PointerEventData eventData) { AudioManager.audioManager.PlayEnterAudio();//將播放觸發提示音 if (gameObject.GetComponent<Animation>()!=null) { if ( gameObject.GetComponent<Animation>() .isPlaying) { return; } gameObject.GetComponent<Animation>().wrapMode = WrapMode.Loop; gameObject.GetComponent<Animation>().Play(); } } //鼠標離開時關閉動畫 public void OnPointerExit(PointerEventData eventData) { if ( gameObject.GetComponent<Animation>() != null ) { if ( gameObject.GetComponent<Animation>().isPlaying ) { gameObject.GetComponent<Animation>().wrapMode = WrapMode.Once; return; } gameObject.GetComponent<Animation>().Stop(); } } ``` **Mouse相關的函式** ![](https://i.imgur.com/vpa5Je1.png) **游標點擊有兩種方式(on mouse click 和 raycasts)** ``` public class ExampleClass : MonoBehaviour { void OnMouseDown() { print (name); } } ``` Raycasts  ``` public class RaycastExample : MonoBehaviour { Ray ray; RaycastHit hit; void Update() { ray = Camera.main.ScreenPointToRay(Input.mousePosition); if(Physics.Raycast(ray, out hit)) //像是滑鼠點擊(擊中所選) {//放置所要顯示的內容 if(Input.GetMouseButtonDown(0)) print(hit.collider.name); } } } ``` * 把圖片設置為Sprite(UI介面可以用),圖片只是Texture而已,只能作貼圖使用。Unity3D 使用脚本来控制 UI 的 Image 顯示的圖片 ![](https://i.imgur.com/vOairSu.png)