ScriptableObject 的使用

ScriptableObject 的一些特点:

1.ScriptableObject 数据存储在 asset 资源文件中,类似 unity 材质或纹理资源,如果在运行时改变了它的值则就是真的改变了
2.ScriptableObject 资源在实例化时是被引用,而非像 Prefab 或其他 GameObject 一样是复制(实际场景中会存在多个 GameObject),所有 ScriptableObject 可以节省 memory

3.传统保存数据并调用可使用 playerprefs、json、xml,而 ScriptableObject  提供了一种新的更便捷与友好的方法(通过 inspector 可视化的编辑需要存储的数据)

创建 ScriptableObject (使用菜单创建)

注意:如果 ScriptableObject 中使用自定义类型,则需要为自定义类加上 [System.Serializable] 属性

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

[CreateAssetMenu(menuName = "ScriptableObject/Weapon")]
public class Weapon : ScriptableObject {

	public string weaponName;
	public Sprite sprite;
	public Color color = Color.white;
	public ColliderType colliderType = ColliderType.None;

	public enum ColliderType {
		None = 0,
		Sprite = 1,
		Grid = 2
	}

}

使用 ScriptableObject

using UnityEngine;

public class GameManager : MonoBehaviour {

	public Weapon weapon;

	void Start() {
		transform.Find("Gun").GetComponent().sprite = weapon.sprite;
		Debug.Log(weapon.name);
	}

}

你可能感兴趣的:(Unity)