当前位置:网站首页>Unity给自己的脚本添加类似编辑器扩展的功能案例ContextMenu的使用

Unity给自己的脚本添加类似编辑器扩展的功能案例ContextMenu的使用

2022-07-04 17:40:00 charlsdm

给自己的物体附加名字最主要提升自己的开发效率,下边就举一个例子来说明一下,下边是放上我的代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class NameKeyValueString : MonoBehaviour
{
    

    public string NameKey = "null";

    public Sprite MySprite = null;
    // Start is called before the first frame update
    void Start()
    {
    
    
        if(this.GetComponent<Image>()!=null||this.GetComponent<SpriteRenderer>()!=null)
        {
    
            if(this.GetComponent<Image>()!=null)
            {
    
                if (GameResAssetBundle.GameResSprite.ContainsKey(NameKey))
                    this.GetComponent<Image>().sprite = GameResAssetBundle.GameResSprite[NameKey];
                else
                    Debug.Log("输入的NameKey不包含请重新输入");
            }
            else if(this.GetComponent<SpriteRenderer>()!=null)
            {
    
                if (GameResAssetBundle.GameResSprite.ContainsKey(NameKey))
                    this.GetComponent<SpriteRenderer>().sprite = GameResAssetBundle.GameResSprite[NameKey];
                else
                    Debug.Log("输入的NameKey不包含请重新输入");
            }
        }
    }

    [ContextMenu("自动给我写的脚本添加名字")]
    public void AddNameKeyMyName()
    {
    
        string myname = null;

        if(this.GetComponent<Image>()!=null||this.GetComponent<SpriteRenderer>()!=null)
        {
    
            if(this.GetComponent<Image>()!=null)
            {
    
                myname = this.GetComponent<Image>().sprite.name;
            }
            else if(this.GetComponent<Image>()!=null)
            {
    
                myname = this.GetComponent<SpriteRenderer>().sprite.name;
            }
        }

        if(myname!=null)
        {
    
            NameKey = myname;
        }

    }

    [ContextMenu("自动给我原本的图片赋值为空")]
    public void ClearPictureOrSpriteOrigionName()
    {
    
        string myname = null;

        if (this.GetComponent<Image>() != null || this.GetComponent<SpriteRenderer>() != null)
        {
    
            if (this.GetComponent<Image>() != null)
            {
    
                myname = this.GetComponent<Image>().sprite.name;
            }
            else if (this.GetComponent<Image>() != null)
            {
    
                myname = this.GetComponent<SpriteRenderer>().sprite.name;
            }
        }

        if (myname != null)
        {
    
            if (this.GetComponent<Image>() != null)
            {
    
                this.GetComponent<Image>().sprite = null;
            }
            else if (this.GetComponent<Image>() != null)
            {
    
                this.GetComponent<SpriteRenderer>().sprite = null;
            }
        }
    }
   
}

原网站

版权声明
本文为[charlsdm]所创,转载请带上原文链接,感谢
https://blog.csdn.net/charlsdm/article/details/125601516