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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值