使用ScriptableObject创建.asset文件

.asset一般用来存储一些配置,比如SDK初始化的相关参数。

using System.Collections.Generic;
using UnityEngine;

namespace XXX
{
    [CreateAssetMenu(fileName="xxx", menuName="xxx")]
    public class CommonConfig : ScriptableObject
    {
        [HideInInspector]
        public List<string> Keys;

        [HideInInspector]
        public List<string> Values;

        [System.Serializable]
        public class Param
        {
            public string strA = "";
            public string strB = "";
            public string strC = "";
            public string strD = "";
        }

        public Param paramXXA = null;
        public Param paramXXB = null;

        private Dictionary<string, string> Map;

        private static CommonConfig instance;

        public static CommonConfig Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = (CommonConfig)ResourceManager.LoadAsset("assets/xxx.asset", typeof(CommonConfig));
                }

                return instance;
            }
        }

        private void Awake()
        {
            UpdateData();
        }

        private void UpdateData()
        {
            Map = new Dictionary<string, string>(Keys.Count);

            for (int i = 0; i < Keys.Count; i++)
            {
                Map.Add(Keys[i], Values[i]);
            }
        }

        public string Get(string key)
        {
            string value;
            if (Map.TryGetValue(key, out value))
            {
                return value;
            }

            return key;
        } 
    }
}

定义为public的变量就存储在xxx.asset中,通过 CommonConfig.Instance.Get 直接获取数据。

 

如果在运行时需要修改数据,需要使用下面的

EditorUtility.SetDirty(CommonConfig.Instance);
AssetDatabase.SaveAssets();
posted @ 2017-09-27 19:12  meteoric_cry  阅读(493)  评论(0编辑  收藏  举报