Unity如何在新建Image或者Text的时候默认不勾选RaycastTarget

本文介绍了如何在Unity开发中避免默认勾选RaycastTarget对性能的影响,通过创建自定义脚本UICreation,在创建TextMeshProUGUI和Image时自动设置raycastTarget为false,提高项目效率。
摘要由CSDN通过智能技术生成

默认勾选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;
    }
}

#使用效果
在这里插入图片描述

  • 16
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值