7.0ScriptableObject创建数据

2021-02-18  本文已影响0人  莫忘初心_倒霉熊

创建一个ScriptableObject脚本

方式一

ScriptableObject脚本需要继承自ScriptableObject。如下:

using UnityEngine;

[CreateAssetMenu(fileName ="LevelSettingsScriptableObject",menuName ="CreateLevelSettingsScriptableObject",order =0)]
public class LevelSettings : ScriptableObject
{
    public float TotalTime = 60;
    public AudioClip BGM;
    public Sprite Background;
}

CreateAssetMenu属性用于创建一个右键菜单,如图:


CreateAssetMenu属性
LevelSettingsScriptableObject

方式二

除此我们也可以自定义一个菜单创建ScriptableObject,代码如下:

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

public class MenuItems 
{       
    [MenuItem("Tools/Level Creator/New Level Settings")]
    private static void NewLevelSettings()
    {
        string path = EditorUtility.SaveFilePanelInProject("New Level Settings", "LevelSettings", "asset",
            "Define the name for the LevelSettings asset.");
        if (!string.IsNullOrEmpty(path))
        {
            CreateAsset<LevelSettings>(path);
        }
    }    
    public static T CreateAsset<T>(string path) where T:ScriptableObject
    {
        T dataClass = ScriptableObject.CreateInstance<T>();
        AssetDatabase.CreateAsset(dataClass,path);
        AssetDatabase.Refresh();
        AssetDatabase.SaveAssets();
        return dataClass;
    }
}

点击如图的菜单即可。


自定义菜单

ScriptableObject使用

using UnityEngine;

public class Test : MonoBehaviour
{
    public LevelSettings levelSettings;
    void Start()
    {
        levelSettings = ScriptableObject.CreateInstance<LevelSettings>();
        Debug.Log(levelSettings.TotalTime);     //60
        levelSettings.TotalTime = 10;
        Debug.Log(levelSettings.TotalTime);     //10
        Debug.Log(ScriptableObject.CreateInstance<LevelSettings>().TotalTime);      //60
    }
}

另一种使用方式,首先创建一个ScriptableObject资源,然后在赋值给脚本,如图



TotalTime默认值为60,如图:


默认值
当通过脚本修改TotalTime为10时,即使停止运行游戏,LevelSettings的TotalTime也会修改为10,这一点需要尤为注意。
脚本如下:
using UnityEngine;

public class Test : MonoBehaviour
{
    public LevelSettings levelSettings;
    void Start()
    {
        levelSettings.TotalTime = 10;
    }
}
修改之后,停止游戏
上一篇 下一篇

猜你喜欢

热点阅读