C/C++教程

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}");
        }
    }
}
这篇关于Unity(二十三):ScriptableObject的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!