Unity3D 灵活创建.Asset配置文件

简介

在游戏开发中,我们经常要对一些数据预先配置,比如不同角色的属性,武器的各项数值等等,一般可通过XML配置. 此外还可以用Unity自带的.Asset资源配置文件配置数据,下面介绍一下如何灵活快速的创建.Asset文件并使用.

转载请注明出处

相比XML配置文件, Asset文件更加直观而且支持直接配置如 GameObject、Sprite、AudioClip等更加高级的对象,基本上除了接口、事件 都可以通过Asset文件配置 , 所以说灵活性上比XML要更强一点.

插件演示

  • 首先创建一个继承于ScriptableObject 类的对象
[System.Serializable]
public class DemoConfig : ScriptableObject {

    public string userName;

    public int userID;

    public GameObject userObject;

    public Sprite sprite;

    public AudioClip audioClip;

    public void print() {
        Debug.Log(string.Format("name: {0} id: {1}" , userName , userID));
    }
}
  • 使用UConfig创建对应的Asset文件

创建Asset配置文件

创建成功

  • 配置各项属性
    这里写图片描述

创建Asset文件

创建Asset文件的核心代码只有一句, 那就是通过ScriptableObject.CreateInstance()方法, 这个方法允许传入一个类名并创建对应的资源配置文件,以下代码如下.

static void CreateAsset()
        {
            //class_Name表示类名 , config_Name表示要创建的配置文件名称 , file_floder表示创建路径
            if (class_Name.Length == 0 || config_Name.Length == 0 || file_floder.Length == 0)
            {
                Debug.LogError(string.Format("[UConfig]: 创建失败 , 信息不完整!"));
                return;
            }
            ScriptableObject config = ScriptableObject.CreateInstance(class_Name);

            if (config == null)
            {
                Debug.LogError(string.Format("[UConfig]: 创建失败 , 类名无法识别! --> {0}", class_Name));
                return;
            }
            // 自定义资源保存路径
            string path = file_floder;
            //如果项目总不包含该路径,创建一个
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            config_Name = config_Name.Replace(".asset", "");
            path = string.Format("{0}/{1}.asset", file_floder, config_Name);
            string defFilePath = "Assets/" + config_Name + ".asset";
            // 生成自定义资源到指定路径
            AssetDatabase.CreateAsset(config, defFilePath);
            File.Move(Application.dataPath + string.Format("/{0}.asset" , config_Name), path);
            AssetDatabase.Refresh();
            Debug.Log(string.Format("<color=yellow>[UConfig]: 创建成功 ! --> {0}</color>", path));
            configWindow.Close();
        }

读取配置好的Asset文件

通过以上方式创建的配置文件可以作为一个与Prefab资源对待, 并且可以随其他prefab资源一样被打成AssetBundle包动态加载 , 理所当然的可以实现所谓的热更配置表.

加载的代码就用 Resources.Load(“fileName”); 就可以了,也可以预先挂着到某一个代码的属性中,然后直接通过as强转.

其他

有需要的伙伴可以访问我的码云下载源码,有更详细的代码,供大家参考


点击以下图标前往源码 :

Fork me on Gitee

(顺便Stars一下吧 ^_^)

猜你喜欢

转载自blog.csdn.net/qq_16763249/article/details/80217467