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

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

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;
            }
        }
    }
   
}

猜你喜欢

转载自blog.csdn.net/charlsdm/article/details/125601516