栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 游戏开发 > 其他

【Unity】ScriptableObject的使用以及通过代码的加载与保存方式

其他 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【Unity】ScriptableObject的使用以及通过代码的加载与保存方式

官方地址:https://docs.unity3d.com/2018.4/Documentation/Manual/class-ScriptableObject.html

可将数据存储为工程的资源文件,和一般的json与xml等数据文件比起来,他的可视化就好太多了,直接能在Inspector面板看到数据,类似这样的:

也可以直接在面板上修改,作为一些配置文件也是很不错的选择.

第一步:创建ScriptableObject脚本
using UnityEngine;

// 右键菜单
[CreateAssetMenu(menuName = "ScriptableObjects/CreateCubeScriptableObject")]
public class CubeScriptableObject : ScriptableObject
{
    public Vector3 position = default;
    public Vector3 rotation = default;
    public Vector3 scale = Vector3.one;
    public Color color = Color.white;
}
  第二步:创建资源文件asset

在Assets目录下可以找到对应菜单(Project面板中右键也能看到)

点击就能创建一个带默认值的资源 asset,可以在面板直接进行编辑操作,就可以将参数数据持久化的保存在当前asset文件中.

  第三步:代码中使用
using UnityEngine;

public class CubeScriptableObjectTest : MonoBehaviour
{
    public CubeScriptableObject redCubeSO;
    public CubeScriptableObject greenCubeSO;
    public GameObject Cube;
    // Start is called before the first frame update
    void Start()
    {
        CreateCube(redCubeSO);
        CreateCube(greenCubeSO);
    }

    //从ScriptableObject文件中获取数据并创建Cube
    void CreateCube(CubeScriptableObject cubeSO){
        GameObject cubeGO = GameObject.Instantiate(Cube);
        Transform ts = cubeGO.transform;
        //读取CubeScriptableObject中的数据并赋值到新建的Cube上
        ts.position = cubeSO.position;
        ts.localScale = cubeSO.scale;
        ts.localEulerAngles = cubeSO.rotation;
        cubeGO.GetComponent().material.color = cubeSO.color;
    }
}

 这里创建了两个scriptableObjectAsset文件(redCube和greenCube),简单起见直接通过拖拽的方式进行关联.

运行后可以看到生成的Cube参数就是从asset文件中获取的数据.

代码操作的保存与读取:

通过代码获取ScriptableObject文件时,就通过加载文件的方式,通过路径加载:

CubeScriptableObject cubeAsset = AssetDatabase.LoadAssetAtPath(@"Assets/ScriptableObject/blueCube.asset");
        //do something

 通过代码保存ScritableObject的方式:

void SaveAsset(){
        CubeScriptableObject cubeAsset = ScriptableObject.CreateInstance();
        cubeAsset.position = new Vector3(1,2,3);
        cubeAsset.rotation = new Vector3(4,5,6);
        cubeAsset.scale = new Vector3(1,1,1);
        cubeAsset.color = Color.blue;
        AssetDatabase.CreateAsset(cubeAsset, @"Assets/ScriptableObject/blueCube.asset");
        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
    }

 

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/901360.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号