RaycastTarget:是否標記為光線投射目標
:勾選表示鼠標點擊到該物體后不再穿透到下面的物體
:取消勾選則穿透該物體
在拼UI的過程中往往會添加很多圖片和文字,但是很容易會忽略的其中一點就是把無用的RaycastTarget去掉,因為開啟此選項,組件雖然不需要接受射線,但是它依然在工作且消耗性能。
RaycastTarget 如果被勾選的過多的話, 效率必然會低;編輯狀態下,便捷的方式查看UI交互包含 RayCastTarget 的UI元素,快速定位勾選取消不必要的UI交互,從而提高效率。
方法具體如下:
在場景中添加兩個 Image 和 一個 Button UI 元素,其中取消一個 Image 的Raycast Target
創建相關腳本,腳本的代碼和代碼說明如下:
1 using System.Collections; 2 using System.Collections.Generic; 3 using UnityEngine; 4 using UnityEngine.UI; 5 6 public class RaycastTargetOrientation : MonoBehaviour 7 { 8 // 定義一個靜態變量保存UI四個角點位置信息 9 private static Vector3[] UIFourCorners = new Vector3[4]; 10 11 private void OnDrawGizmos() 12 { 13 // 獲取所有 UI元素 14 MaskableGraphic[] maskableGraphics = GameObject.FindObjectsOfType<MaskableGraphic>(); 15 // 遍歷所有元素 16 foreach (MaskableGraphic mg in maskableGraphics) 17 { 18 // 如果元素勾選 raycastTarget,則進行划線顯示 19 if (mg.raycastTarget == true) 20 { 21 RectTransform rect = mg.transform as RectTransform; 22 rect.GetWorldCorners(UIFourCorners); 23 Gizmos.color = Color.red; 24 25 for (int i = 0; i < 4; i++) 26 { 27 Gizmos.DrawLine(UIFourCorners[i], UIFourCorners[(i + 1) % 4]); 28 } 29 } 30 } 31 } 32 33 }
腳本編譯正確,回到Unity,在場景中添加一個 GameObject,並掛載上腳本,在Scene窗口即可看到勾選 Raycast Target的UI元素被紅框標記,具體如下圖:
再次取消另一個不必要有交互的 Image 的 Raycast Target,在Scene窗口即可看到她的UI 紅框消失了,具體如下圖: