Unity ScriptableObject简单使用

可以利用ScriptableObject来存储一些数据

创建脚本MyScriptableObject
using System.Collections.Generic;
using UnityEngine;

 //ScriptableObject好像不能存储字典类型
//可以直接在Project右键创建
[CreateAssetMenu]
public class MyScriptableObject : ScriptableObject
{
    public string myName = "";
    private void OnEnable()
    {
    }
    private void OnDisable()
    {
    }
    private void OnDestroy()
    {
    }
}
创建、打包、加载
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;

public class BuildEditor : EditorWindow
{
    //创建一个 MyScriptableObject 对象
    [MenuItem("MyScriptableObject/Create")]
    static void CreateScriptObj()
    {
        //ScriptableObject myScriptable = CreateInstance(typeof(MyScriptableObject));
        MyScriptableObject myScriptable = new MyScriptableObject();
        myScriptable.myName = "通讯录";

        //创建.asset (路径必须在 Assets 下)
        AssetDatabase.CreateAsset(myScriptable, "Assets/ScriptableObjects/mySO.asset");
    }


    //把 MyScriptableObject 打包成 AssetBundle,以方便外部加载
    [MenuItem("MyScriptableObject/Build")]
    static void BuildScriptObj()
    {
        List<AssetBundleBuild> AssetBundleBuildList = new List<AssetBundleBuild>();

        List<string> assetNamesArray = new List<string>();
        List<string> addressableNamesArray = new List<string>();
        assetNamesArray.Add("Assets/ScriptableObjects/mySO.asset");
        addressableNamesArray.Add("mySO");

        AssetBundleBuild assetBundleBuild = new AssetBundleBuild();
        //assetNames:资源在项目中的路径,加上后缀名
        assetBundleBuild.assetNames = assetNamesArray.ToArray();
        //addressableNames:资源名称(之后 LoadAsset 时会用到)
        assetBundleBuild.addressableNames = addressableNamesArray.ToArray();
        //assetBundleName:生成的 AssetBundle 的名称
        assetBundleBuild.assetBundleName = "ScriptableObjects";
        //assetBundleVariant:AssetBundle 的后缀名
        assetBundleBuild.assetBundleVariant = "unity3d";
        AssetBundleBuildList.Add(assetBundleBuild);
        //以 LZ4 压缩方式打包资源
        BuildPipeline.BuildAssetBundles(@"E:\My\AssetBundle", AssetBundleBuildList.ToArray(), BuildAssetBundleOptions.ChunkBasedCompression, BuildTarget.StandaloneWindows64);
    }


    //加载一个 AssetBundle
    [MenuItem("MyScriptableObject/Load")]
    static void LoadScriptObj()
    {
        AssetBundle mySO_AB = AssetBundle.LoadFromFile(@"E:\My\AssetBundle\ScriptableObjects.unity3d");

        //从 AssetBundle 中加载一个 Asset 文件
        MyScriptableObject mySO = mySO_AB.LoadAsset<MyScriptableObject>("mySO");
        Debug.Log(mySO.myName);

        mySO_AB.Unload(false);
    }
}
创建的ScriptableObject对象.png

生成的AssetBundle.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容