【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<GameObject>(Cube);
        Transform ts = cubeGO.transform;
        //读取CubeScriptableObject中的数据并赋值到新建的Cube上
        ts.position = cubeSO.position;
        ts.localScale = cubeSO.scale;
        ts.localEulerAngles = cubeSO.rotation;
        cubeGO.GetComponent<Renderer>().material.color = cubeSO.color;
    }
}

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

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

代码操作的保存与读取:

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

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

 通过代码保存ScritableObject的方式:

void SaveAsset(){
        CubeScriptableObject cubeAsset = ScriptableObject.CreateInstance<CubeScriptableObject>();
        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();
    }

 

 

  • 14
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值