赞
踩
官方地址:https://docs.unity3d.com/2018.4/Documentation/Manual/class-ScriptableObject.html
可将数据存储为工程的资源文件,和一般的json与xml等数据文件比起来,他的可视化就好太多了,直接能在Inspector面板看到数据,类似这样的:
也可以直接在面板上修改,作为一些配置文件也是很不错的选择.
- 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;
- }
在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();
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。