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 && 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 | 当对象加载时调用此函数。 |
OnValidate | Editor-only function that Unity calls when the script is loaded or a value changes in the Inspector. |
Reset | 重置为默认值。 |
GetInstanceID | Gets the instance ID of the object. |
ToString | 返回对象的名称。 |
Destroy | 移除 GameObject、组件或资源。 |
DestroyImmediate | 立即销毁对象 /obj/。强烈建议您改用 Destroy。 |
DontDestroyOnLoad | 在加载新的 Scene 时,请勿销毁 Object。 |
FindAnyObjectByType | Retrieves any active loaded object of Type type. |
FindFirstObjectByType | Retrieves the first active loaded object of Type type. |
FindObjectOfType | 返回第一个类型为 type 的已加载的激活对象。 |
FindObjectsByType | Retrieves a list of all loaded objects of Type type. |
FindObjectsOfType | Gets a list of all loaded objects of Type type. |
Instantiate | 克隆 original 对象并返回克隆对象。 |
bool | 该对象是否存在? |
operator != | 比较两个对象是否引用不同的对象。 |
operator == | 比较两个对象引用,判断它们是否引用同一个对象。 |
Did you find this page useful? Please give it a rating:
Thanks for rating this page!
What kind of problem would you like to report?
Thanks for letting us know! This page has been marked for review based on your feedback.
If you have time, you can provide more information to help us fix the problem faster.
Provide more information
You've told us this page needs code samples. If you'd like to help us further, you could provide a code sample, or tell us about what kind of code sample you'd like to see:
You've told us there are code samples on this page which don't work. If you know how to fix it, or have something better we could use instead, please let us know:
You've told us there is information missing from this page. Please tell us more about what's missing:
You've told us there is incorrect information on this page. If you know what we should change to make it correct, please tell us:
You've told us this page has unclear or confusing information. Please tell us more about what you found unclear or confusing, or let us know how we could make it clearer:
You've told us there is a spelling or grammar error on this page. Please tell us what's wrong:
You've told us this page has a problem. Please tell us more about what's wrong:
Thank you for helping to make the Unity documentation better!
Your feedback has been submitted as a ticket for our documentation team to review.
We are not able to reply to every ticket submitted.