0评论

Unity生成.assets文件

文章来自CSDN博客 2018-08-08 29浏览

想免费获取内部独家PPT资料库?观看行业大牛直播?点击加入腾讯游戏学院游戏开发行业精英群711501594

在游戏开发中,经常会用到一些配置文件保存一些数据,然后项目运行中读取这些配置文件中的数据在游戏中使用。下面就介绍一下使用可序列化类保存配置,并且将可序列化类保存成Unity的文件(.asset)。

工具类:
using UnityEngine;
using UnityEditor;
using System.IO;
public static class ScriptableObjectUtility
{
    public static void CreateAsset<T>() where T : ScriptableObject
    {
        T asset = ScriptableObject.CreateInstance<T>();
        string path = AssetDatabase.GetAssetPath(Selection.activeObject);
        if( string.IsNullOrEmpty( path ) )
        {
            Debug.LogError("Not select files, select files first! ");
            return;
        }
        else if (!string.IsNullOrEmpty(Path.GetExtension(path)))
        {
            path = path.Replace(Path.GetFileName(AssetDatabase.GetAssetPath(Selection.activeObject)), "");
        }
        string assetPathAndName = AssetDatabase.GenerateUniqueAssetPath(path + "/New" + typeof(T).ToString() + ".asset");
        AssetDatabase.CreateAsset(asset, assetPathAndName);
        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
        EditorUtility.FocusProjectWindow();
        Selection.activeObject = asset;
    }
}

菜单按钮:
using UnityEngine;
using UnityEditor;
using System;
public class CreateAssets
{
    [MenuItem("Assets/Create assets")]
    public static void CreateAsset()
    {
        ScriptableObjectUtility.CreateAsset<AssetsScripts>();
    }
}

被生成对象,ScriptableObject类型:
using UnityEngine;
using UnityEditor;
using System;
public class AssetsScripts : ScriptableObject
{
    public string playerName = "Yu Xikuo";
}
来自:https://blog.csdn.net/yuxikuo_1/article/details/52812446