其他分享
首页 > 其他分享> > Unity(二十三):ScriptableObject

Unity(二十三):ScriptableObject

作者:互联网

创建Asset资源 - ScriptableObject

在这里插入图片描述
在这里插入图片描述

Assets\Editor\Create_ScriptableObject.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

public class Create_ScriptableObject
{
    [MenuItem("Assets/Create/CreateAsset", false, 0)]
    static void CreateAsset()
    {
        Armory script = ScriptableObject.CreateInstance<Armory>();
        script.arsenalList = new List<Armory.ArsenalInfo>();

        script.arsenalList.Add(new Armory.ArsenalInfo { name = "狙击枪", code = "98K" });
        script.arsenalList.Add(new Armory.ArsenalInfo { name = "步枪", code = "AK-47" });
        script.arsenalList.Add(new Armory.ArsenalInfo { name = "步枪", code = "Skr" });

        // 将资源保存到本地
        AssetDatabase.CreateAsset(script, "Assets/Resources/Armory.asset");
        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
    }
}

Assets\Scripts\Armory.cs

using System.Collections.Generic;
using UnityEngine;

[CreateAssetMenu]
public class Armory : ScriptableObject
{
    public List<ArsenalInfo> arsenalList;

    [System.Serializable]
    public class ArsenalInfo
    {
        public string name;
        public string code;
    }
}

Assets\Scripts\CubeScript.cs

using UnityEngine;

public class CubeScript : MonoBehaviour
{
    private void Start()
    {
    	// 访问Resources文件夹下的文件
        Armory script = Resources.Load<Armory>("Armory");
        foreach (var arsenalInfo in script.arsenalList)
        {
            Debug.Log($"name: {arsenalInfo.name}; code: {arsenalInfo.code}");
        }
    }
}

标签:code,ScriptableObject,二十三,script,Unity,arsenalList,Armory,using,public
来源: https://blog.csdn.net/weixin_43526371/article/details/122761796