Version: 2023.2

ScriptableObject

class in UnityEngine

/

继承自:Object

切换到手册

描述

A class you can derive from if you want to create objects that live independently of GameObjects.

Use ScriptableObjects to centralise data in a way that can be conveniently accessed from scenes and assets within a project.

Instantiate ScriptableObject objects with CreateInstance.

You can save ScriptableObjects to asset files either from the Editor UI (see CreateAssetMenuAttribute), or by calling AssetDatabase.CreateAsset from a script. You can also generate ScriptableObjects as an output from a ScriptedImporter. See AssetImportContext.AddObjectToAsset.

If a ScriptableObject has not been saved to an asset, and it is referenced from an object in a scene, Unity serializes it directly into the scene file. For ScriptableObjects that have only a single persistent instance within a project, use the ScriptableSingleton<T0> base class.

Access previously saved objects using AssetDatabase, for example AssetDatabase.LoadAssetAtPath. When a ScriptableObject is referenced from a field on a MonoBehaviour, the ScriptableObject is automatically loaded, so a script can simply use the value of the field to reach it.

The C# fields of a ScriptableObject are serialized exactly like fields on a MonoBehaviour. See Script Serialization for details. representation for that sort of data.

Classes that include big arrays, or other potentially large data, should be declared with the PreferBinarySerialization attribute, because YAML is not an efficient representation for that sort of data.

After a ScriptableObject is destroyed, the C# object remains in memory until garbage is collected. A ScriptableObject in this state acts as if it is null. For example, it returns true for a "obj == null" check. However, this class doesn't support the null-conditional operator (?.) and the null-coalescing operator (??).

The following example demonstrates a typical use of a ScriptableObject: different types of vehicle parameters are represented in the fields of a VehicleTypeInfo class, derived from ScriptableObject. Each type of vehicle would have its own asset file, with the parameter values set appropriately for the type. Each instance of the vehicle in the game would have a reference to the asset corresponding to its type, rather than keeping its own redundant copy of each parameter. This design makes it convenient to tweak vehicle behaviour in a central location. It is also good for performance, especially in cases where the size of the shared data is substantial.

The first script of the example implements a class derived from ScriptableObject.

using UnityEngine;

[CreateAssetMenu] public class VehicleTypeInfo : ScriptableObject { // Class that represents a specific type of vehicle [Range(0.1f, 100f)] public float m_MaxSpeed = 0.1f;

[Range(0.1f, 10f)] public float m_MaxAcceration = 0.1f;

// This class could have many other vehicle parameters, such as Turning Radius, Range, Damage etc }

The second script implements a MonoBehaviour that uses the ScriptableObject.

using UnityEngine;
using UnityEditor;

public class VehicleInstance : MonoBehaviour { // Snippet of a MonoBehaviour that would control motion of a specific vehicle. // In PlayMode it accelerates up to the maximum speed permitted by its type

[Range(0f, 200f)] public float m_CurrentSpeed;

[Range(0f, 50f)] public float m_Acceleration;

// Reference to the ScriptableObject asset public VehicleTypeInfo m_VehicleType;

public void Initialize(VehicleTypeInfo vehicleType) { m_VehicleType = vehicleType; m_CurrentSpeed = 0f; m_Acceleration = Random.Range(0.05f, m_VehicleType.m_MaxAcceration); }

void Update() { m_CurrentSpeed += m_Acceleration * Time.deltaTime;

// Use parameter from the ScriptableObject to control the behaviour of the Vehicle if (m_VehicleType &amp;&amp; m_VehicleType.m_MaxSpeed < m_CurrentSpeed) m_CurrentSpeed = m_VehicleType.m_MaxSpeed;

gameObject.transform.position += gameObject.transform.forward * Time.deltaTime * m_CurrentSpeed; } }

public class ScriptableObjectVehicleExample { [MenuItem("Example/Setup ScriptableObject Vehicle Example")] static void MenuCallback() { // This example programmatically performs steps that would typically be performed from the Editor's user interface // to creates a simple demonstration. When going into Playmode the three objects will move according to the limits // set by their vehicle type.

// Step 1 - Create or reload the assets that store each VehicleTypeInfo object. VehicleTypeInfo wagon = AssetDatabase.LoadAssetAtPath<VehicleTypeInfo>("Assets/VehicleTypeWagon.asset"); if (wagon == null) { // Create and save ScriptableObject because it doesn't exist yet wagon = ScriptableObject.CreateInstance<VehicleTypeInfo>(); wagon.m_MaxSpeed = 5f; wagon.m_MaxAcceration = 0.5f; AssetDatabase.CreateAsset(wagon, "Assets/VehicleTypeWagon.asset"); }

VehicleTypeInfo cruiser = AssetDatabase.LoadAssetAtPath<VehicleTypeInfo>("Assets/VehicleTypeCruiser.asset"); if (cruiser == null) { cruiser = ScriptableObject.CreateInstance<VehicleTypeInfo>(); cruiser.m_MaxSpeed = 75f; cruiser.m_MaxAcceration = 2f; AssetDatabase.CreateAsset(cruiser, "Assets/VehicleTypeCruiser.asset"); }

// Step 2 - Create some example vehicles in the current scene { var vehicle = GameObject.CreatePrimitive(PrimitiveType.Sphere); vehicle.name = "Wagon1"; var vehicleBehaviour = vehicle.AddComponent<VehicleInstance>(); vehicleBehaviour.Initialize(wagon); }

{ var vehicle = GameObject.CreatePrimitive(PrimitiveType.Sphere); vehicle.name = "Wagon2"; var vehicleBehaviour = vehicle.AddComponent<VehicleInstance>(); vehicleBehaviour.Initialize(wagon); }

{ var vehicle = GameObject.CreatePrimitive(PrimitiveType.Cube); vehicle.name = "Cruiser1"; var vehicleBehaviour = vehicle.AddComponent<VehicleInstance>(); vehicleBehaviour.Initialize(cruiser); } } }

静态函数

CreateInstance创建脚本化对象的实例。

消息

Awake当 ScriptableObject 脚本启动时调用此函数。
OnDestroy当脚本化对象将销毁时调用此函数。
OnDisable当脚本化对象超出范围时调用此函数。
OnEnable当对象加载时调用此函数。
OnValidateEditor-only function that Unity calls when the script is loaded or a value changes in the Inspector.
Reset重置为默认值。

继承的成员

变量

hideFlags该对象应该隐藏、随场景一起保存还是由用户修改?
name对象的名称。

公共函数

GetInstanceIDGets the instance ID of the object.
ToString返回对象的名称。

静态函数

Destroy移除 GameObject、组件或资源。
DestroyImmediate立即销毁对象 /obj/。强烈建议您改用 Destroy。
DontDestroyOnLoad在加载新的 Scene 时,请勿销毁 Object。
FindAnyObjectByTypeRetrieves any active loaded object of Type type.
FindFirstObjectByTypeRetrieves the first active loaded object of Type type.
FindObjectsByTypeRetrieves a list of all loaded objects of Type type.
Instantiate克隆 original 对象并返回克隆对象。

运算符

bool该对象是否存在?
operator !=比较两个对象是否引用不同的对象。
operator ==比较两个对象引用,判断它们是否引用同一个对象。