ScriptableObject[Unity]

ScriptableObject is a class that allows you to store largequantities of shared data independent from script instances. Do notconfuse this class with the similarly named SerializableObject,which is an editor class and fills a different purpose. Considerfor example that you have made a prefab with a script which has anarray of a million integers. The array occupies 4MB of memory andis owned by the prefab. Each time you instantiate that prefab, youwill get a copy of that array. If you created 10 game objects, thenyou would end up with 40MB of array data for the 10 instances.

Unity serializes all primitive types, strings, arrays, lists, typesspecific to Unity such as Vector3 and your custom classes with theSerializable attributeas copies belonging tothe object they were declared in. This means that if you created aScriptableObject and stored the million integers in an array itdeclares then the array will be stored with that instance. Theinstances are thought to own their individual data.ScriptableObject fields, orany UnityEngine.Object fields,such as MonoBehaviour, Mesh, GameObject and so on, are storedby reference as opposedto by value. If you have a script with a reference to theScriptableObject with the million integers, Unity will only store areference to the ScriptableObject in the script data. TheScriptableObject in turn stores the array. 10 instances of a prefabthat has a reference to a ScriptableObject, that holds 4MB data,would total to roughly 4MB and not 40MB as discussed in the otherexample.

The intended use case for using ScriptableObject is to reducememory usage by avoiding copies of values, but you could also useit to define pluggable data sets. An example of this would be toimagine a NPC shop in a RPG game. You could create multiple assetsof your custom ShopContents ScriptableObject, each defining a setof items that are available for purchase. In a scenario where thegame has three zones, each zone could offer different tier items.Your shop script would reference a ShopContents object that defineswhat items are available. Please see the scripting reference forexamples.

Tip: When working with ScriptableObject references in theinspector, you can double click the reference field to open theinspector for your ScriptableObject. You can also create a customEditor to define the look of the inspector for your type to helpmanage the data that it represents.

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页