Unity UGUI优化技巧之RaycastTarget
发表于2018-11-09
在拼UI的过程中会添加很多图片文字,但是很容易会忽略其中一点就是把无用的RaycastTarget去掉,因为开启此选项,虽然此组建虽然不需要接受射线,但是它而然工作且消耗性能。
在网上找了2个小工具:
其中一个是在Editor模式下用蓝色框出启用RatcastTarget的组件
Code如下。挂在任意GameObject上即可
#if UNITY_EDITOR using UnityEngine; using System.Collections; using UnityEngine.UI; public class DebugUILine : MonoBehaviour { static Vector3[] fourCorners = new Vector3[4]; void OnDrawGizmos() { foreach (MaskableGraphic g in GameObject.FindObjectsOfType<MaskableGraphic>()) { if (g.raycastTarget) { RectTransform rectTransform = g.transform as RectTransform; rectTransform.GetWorldCorners(fourCorners); Gizmos.color = Color.blue; for (int i = 0; i < 4; i++) Gizmos.DrawLine(fourCorners[i], fourCorners[(i + 1) % 4]); } } } } #endif
第二个是自动取消创建对应Image Text 的RaycastTarget选项(重写unity创建对应组件,创建组建后自动取消选项)
Code 如下
using UnityEngine; using System.Collections; using UnityEditor; using UnityEngine.UI; public class UITools { /// <summary> /// 自动取消RatcastTarget /// </summary> [MenuItem("GameObject/UI/Image")] static void CreatImage() { if (Selection.activeTransform) { if (Selection.activeTransform.GetComponentInParent<Canvas>()) { GameObject go = new GameObject("image", typeof(Image)); go.GetComponent<Image>().raycastTarget = false; go.transform.SetParent(Selection.activeTransform); } } } //重写Create->UI->Text事件 [MenuItem("GameObject/UI/Text")] static void CreatText() { if (Selection.activeTransform) { //如果选中的是列表里的Canvas if (Selection.activeTransform.GetComponentInParent<Canvas>()) { //新建Text对象 GameObject go = new GameObject("text", typeof(Text)); //将raycastTarget置为false go.GetComponent<Text>().raycastTarget = false; //设置其父物体 go.transform.SetParent(Selection.activeTransform); } } } //重写Create->UI->Text事件 [MenuItem("GameObject/UI/Raw Image")] static void CreatRawImage() { if (Selection.activeTransform) { //如果选中的是列表里的Canvas if (Selection.activeTransform.GetComponentInParent<Canvas>()) { //新建Text对象 GameObject go = new GameObject("RawImage", typeof(RawImage)); //将raycastTarget置为false go.GetComponent<RawImage>().raycastTarget = false; //设置其父物体 go.transform.SetParent(Selection.activeTransform); } } } }
来自:https://www.jianshu.com/p/3082ebf8a342