默认勾选RaycastTarget的问题
我们开发中大部分图片和text是不需要射线检测的,但是创建这些UI的时候默认都是勾选。这样子不但会影响项目性能,还会遮挡项目中需要的射线检测。因此我们需要默认不勾选这写选项
使用方法
- 在项目中新建一个脚本“UICreation ”,删掉里面的代码再把下面的代码全部复制进去。
- 创建TextMeshProUGUI,在Hierarchy窗口右键—>UI—>Custom_TextMeshProUGUI
- 创建Image,在Hierarchy窗口右键—>UI—>Custom_Image
using TMPro;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
public class UICreation : Editor
{
[MenuItem("GameObject/UI/Custom_Image")]
public static void CreateImage()
{
CreateUIElement<Image>("Image");
}
[MenuItem("GameObject/UI/Custom_TextMeshProUGUI")]
public static void CreateText()
{
CreateUIElement<TextMeshProUGUI>("TextUGUI");
}
private static void CreateUIElement<T>(string name) where T : Component
{
GameObject parent = Selection.activeGameObject;
if (parent == null || parent.GetComponentInParent<Canvas>() == null)
{
Debug.LogWarning("No Canvas found in the parent hierarchy. Please select a GameObject with a Canvas.");
return;
}
GameObject go = new GameObject(name, typeof(RectTransform), typeof(T));
Graphic graphicComponent = go.GetComponent<Graphic>();
if (graphicComponent != null)
{
graphicComponent.raycastTarget = false;
}
else
{
Debug.LogWarning("The component type T does not have a raycastTarget property.");
}
go.transform.SetParent(parent.transform, false);
go.GetComponent<RectTransform>().localPosition = Vector3.zero;
}
}
#使用效果