zoukankan      html  css  js  c++  java
  • Unity编辑器扩展 Chapter7--使用ScriptableObject持久化存储数据

    Unity编辑器扩展 Chapter7--使用ScriptableObject持久化存储数据

    Unity编辑器扩展 Chapter7--使用ScriptableObject持久化存储数据

    OverView

    API
    ScriptableObject是unity中的一种特别的类型,它不需要挂在场景中的对象上。它可以视作asset资源一样,存储在项目文件中。在一些特殊的情况下要比JSON,XML及TXT方式来存储持久化数据要受益得多。因为unity可以自主序列化和解析该类型,而不需要像其他方式一样需要第三方工具或自己编写解析工具。

    注意:它仍然有Awake,OnEnable,OnDestory等方法可以供你使用,详见上方API

    创建一个ScriptableObject

    需要创建一个ScriptableObject只需要让一个类继承ScriptableObject即可。

    using UnityEngine;
    using System;
    namespace MyScirptableObject {
    [Serializable]
    public class LevelSettings : ScriptableObject {
    	public float gravity = -30;
    	public AudioClip bgm;
    	public Sprite background;
    	}
    }
    

    创建一个包含该数据类的asset资源

    可以通过多种方式来创建该资源,主要使用 ScriptableObject.CreateInstance 方法

    方式一:使用tool菜单创建

    注意:在使用Editor类中添加如下方法

    public static T CreateAsset<T>(string path)
    where T : ScriptableObject {
    T dataClass = (T) ScriptableObject.CreateInstance<T>();
    AssetDatabase.CreateAsset(dataClass, path);
    AssetDatabase.Refresh();
    AssetDatabase.SaveAssets();
    return dataClass;
    }
    
    [MenuItem ("Tools/Level Creator/New Level Settings")]
    private static void NewLevelSettings () {
    string path = EditorUtility.SaveFilePanelInProject(
    "New Level Settings",
    "LevelSettings",
    "asset",
    "Define the name for the LevelSettings asset");
    if(path != "") {
    EditorUtils.CreateAsset<LevelSettings>(path);
    }
    }
    

    效果:

    Menu

    Menu

    方式二:右键Project面板使用Create菜单创建

    using UnityEngine;
    using UnityEngine.Events;
    
    [CreateAssetMenu(menuName= "CreateMyScriptableScript",fileName= "Scripts/MyScriptableScript")]
    public class MyScriptableScript : ScriptableObject
    {
        public string Name;
        public int Level;
        public GameObject Prefab;
        public UnityEvent Event;
    
        public void Instance()
        {
            GameObject go = GameObject.Instantiate(Prefab);
            go.name = Name;
            Event.AddListener(() =>
            {
                Debug.Log(("call event!"));
                foreach (var renderer in go.transform.GetChild(0).GetComponentsInChildren<Renderer>())
                {
                    renderer.material.color = Color.red;
                }
                
            });
            Event.Invoke();
        }
    
    }
    
    

    效果:

    Create

    Create

    创建后我们就可以在Inspector面板中在为该asset添加数据

    DataAsset

    DataAsset

    使用ScirptableObject存储的数据

    直接在使用的类中声明需要的ScriptableObject类型即可。然后就可以将之前创建好的asset资源添加到上面,我们就可以使用该方式存储的数据了。

    Use

    Use

  • 相关阅读:
    Miller-Rabin素性测试
    ###Canny边缘检测算子
    ###SIFT特征
    建立一个免费的网站
    ###C中的extern-static-const关键词
    ###Git使用问题
    ###Fedora下安装Retext
    ###使用phpmailer自动邮件提醒
    Markdown学习
    有线和无线同时连接,选择其一上网
  • 原文地址:https://www.cnblogs.com/Firepad-magic/p/8799380.html
Copyright © 2011-2022 走看看