Scriptableobject unity способы применения

ScriptableObject

A ScriptableObject is a data container that you can use to save large amounts of data, independent of class instances. One of the main use cases for ScriptableObjects is to reduce your Project’s memory usage by avoiding copies of values. This is useful if your Project has a Prefab An asset type that allows you to store a GameObject complete with components and properties. The prefab acts as a template from which you can create new object instances in the scene. More info
See in Glossary that stores unchanging data in attached MonoBehaviour scripts A piece of code that allows you to create your own Components, trigger game events, modify Component properties over time and respond to user input in any way you like. More info
See in Glossary .

Every time you instantiate that Prefab, it will get its own copy of that data. Instead of using the method, and storing duplicated data, you can use a ScriptableObject to store the data and then access it by reference from all of the Prefabs. This means that there is one copy of the data in memory.

Just like MonoBehaviours, ScriptableObjects derive from the base Unity object but, unlike MonoBehaviours, you can not attach a ScriptableObject to a GameObject The fundamental object in Unity scenes, which can represent characters, props, scenery, cameras, waypoints, and more. A GameObject’s functionality is defined by the Components attached to it. More info
See in Glossary . Instead, you need to save them as Assets in your Project.

When you use the Editor, you can save data to ScriptableObjects while editing and at run time because ScriptableObjects use the Editor namespace and Editor scripting. In a deployed build, however, you can’t use ScriptableObjects to save data, but you can use the saved data from the ScriptableObject Assets that you set up during development.

Data that you save from Editor Tools to ScriptableObjects as an asset is written to disk and is therefore persistent between sessions.

This page provides an overview of the ScriptableObject class and its common uses when scripting with it. For an exhaustive reference of every member of the ScriptableObject class, see the ScriptableObject script reference.

Using a ScriptableObject

The main use cases for ScriptableObjects are:

  • Saving and storing data during an Editor session
  • Saving data as an Asset in your Project to use at run time

To use a ScriptableObject, create a script in your application’s Assets Any media or data that can be used in your game or project. An asset may come from a file created outside of Unity, such as a 3D Model, an audio file or an image. You can also create some asset types in Unity, such as an Animator Controller, an Audio Mixer or a Render Texture. More info
See in Glossary folder and make it inherit from the ScriptableObject class. You can use the CreateAssetMenu attribute to make it easy to create custom assets using your class. For example:

With the above script in your Assets folder, you can create an instance of your ScriptableObject by navigating to Assets > Create > ScriptableObjects > SpawnManagerScriptableObject. Give your new ScriptableObject instance a meaningful name and alter the values. To use these values, you need to create a new script that references your ScriptableObject, in this case, a SpawnManagerScriptableObject . For example:

Note: The script file must have the same name as the class.

Читайте также:  Способ продления полосового акта мужчине

Attach the above script to a GameObject in your Scene A Scene contains the environments and menus of your game. Think of each unique Scene file as a unique level. In each Scene, you place your environments, obstacles, and decorations, essentially designing and building your game in pieces. More info
See in Glossary . Then, in the Inspector A Unity window that displays information about the currently selected GameObject, asset or project settings, allowing you to inspect and edit the values. More info
See in Glossary , set the Spawn Manager Values field to the new SpawnManagerScriptableObject that you set up.

Set the Entity To Spawn field to any Prefab in your Assets folder, then click Play in the Editor. The Prefab you referenced in the Spawner instantiates using the values you set in the SpawnManagerScriptableObject instance.

If you’re working with ScriptableObject references in the Inspector, you can double click the reference field to open the Inspector for your ScriptableObject. You can also create a custom Editor to define the look of the Inspector for your type to help manage the data that it represents.

Источник

ScriptableObject

A ScriptableObject is a data container that you can use to save large amounts of data, independent of class instances. One of the main use cases for ScriptableObjects is to reduce your Project’s memory usage by avoiding copies of values. This is useful if your Project has a Prefab that stores unchanging data in attached MonoBehaviour scripts.

Every time you instantiate that Prefab, it will get its own copy of that data. Instead of using the method, and storing duplicated data, you can use a ScriptableObject to store the data and then access it by reference from all of the Prefabs. This means that there is one copy of the data in memory.

Just like MonoBehaviours, ScriptableObjects derive from the base Unity object but, unlike MonoBehaviours, you can not attach a ScriptableObject to a GameObject. Instead, you need to save them as Assets in your Project.

When you use the Editor, you can save data to ScriptableObjects while editing and at run time because ScriptableObjects use the Editor namespace and Editor scripting. In a deployed build, however, you can’t use ScriptableObjects to save data, but you can use the saved data from the ScriptableObject Assets that you set up during development.

Data that you save from Editor Tools to ScriptableObjects as an asset is written to disk and is therefore persistent between sessions.

Using a ScriptableObject

The main use cases for ScriptableObjects are:

  • Saving and storing data during an Editor session
  • Saving data as an Asset in your Project to use at run time

To use a ScriptableObject, create a script in your application’s Assets folder and make it inherit from the ScriptableObject class. You can use the CreateAssetMenu attribute to make it easy to create custom assets using your class. For example:

With the above script in your Assets folder, you can create an instance of your ScriptableObject by navigating to Assets > Create > ScriptableObjects > SpawnManagerScriptableObject. Give your new ScriptableObject instance a meaningful name and alter the values. To use these values, you need to create a new script that references your ScriptableObject, in this case, a SpawnManagerScriptableObject . For example:

Attach the above script to a GameObject in your Scene. Then, in the Inspector, set the Spawn Manager Values field to the new SpawnManagerScriptableObject that you set up.

Читайте также:  Фиброзная оболочка для колбас способ применения

Set the Entity To Spawn field to any Prefab in your Assets folder, then click Play in the Editor. The Prefab you referenced in the Spawner instantiates using the values you set in the SpawnManagerScriptableObject instance.

If you’re working with ScriptableObject references in the Inspector, you can double click the reference field to open the Inspector for your ScriptableObject. You can also create a custom Editor to define the look of the Inspector for your type to help manage the data that it represents.

Источник

Скриптуемый объект (ScriptableObject)

ScriptableObject это класс, который позволяет вам хранить большое количество передаваемой информации независимо от образцов скрипта. Не путайте этот класс с классом под названием SerializableObject, который является классом редактора и служит для других целей. Представьте на мгновение, что вы создали префаб со скриптом, который имеет массив из миллиона целых чисел. Массив занимает 4 мегабайта памяти и принадлежит префабу. Каждый раз создавая экземпляр этого префаба, вы создаёте и экземпляр этого массива. Если вы создадите 10 игровых объектов, тогда в итоге размер занимаемый массивами для этих 10 экземпляров будет равен 40 мегабайтам.

Unity сериализует все типы примитивов, строк, массивов, списков, специфичных типов для Unity, таких как Vector3 и ваших собственных классов с атрибутом Serializable в качестве копий, относящихся к объекту, в котором они определены. Данное означает, что если вы создали класс ScriptableObject и сохранили в нём объявляемый массив из миллиона целых чисел, тогда этот массив будет передаваться вместе с этим образцом. При этом экземпляры считают, что обладают разными данными. Поля ScriptableObject или любые UnityEngine.Object поля, такие как MonoBehaviour, Mesh, GameObject и т.д, в противоположность значениям хранятся в ссылках. Если у вас есть скрипт, ссылающийся на ScriptableObject, содержащий миллион целых чисел, Unity сохранит в данных скрипта лишь ссылку на ScriptableObject. ScriptableObject в свою очередь хранит массив. 10 экземпляров префаба, которые ссылаются на класс ScriptableObject, который использует 4 мегабайта памяти, в итоге заняли бы 4 мегабайта вместо 40, о которых шла речь немного раньше.

Класс ScriptableObject необходимо использовать в тех случаях, когда нужно снизить расход памяти путём избежания копирования значений, но его также можно использовать для определения включаемых наборов данных. В качестве примера для иллюстрации его работы представьте себе NPC магазин в РПГ игре. Вы можете создать несколько ассетов вашего ShopContents (содержимого магазина) ScriptableObject, каждый из которых определял бы набор предметов, доступных для покупки. В случае, когда игра разделена на три зоны, в каждой зоне продаются свои предметы. Скрипт вашего магазина будет ссылаться на объект ShopContents, чтобы определить какие предметы доступны в данный момент. Для большего количества примеров, пожалуйста посетите руководство по скриптингу.

Once you have defined a ScriptableObject-derived class, you can use the CreateAssetMenu attribute to make it easy to create custom assets using your class.

Подсказка: при работе в инспекторе с экземплярами ScriptableObject вы можете дважды нажать на поле ссылки, чтобы открыть инспектор для своего ScriptableObject (скриптуемого объекта). Вы также можете создать пользовательский редактор для определения вида инспектора своего типа, чтобы помочь управлять данными, которые он представляет.

Источник

Три способа построить игру на основе объектов Scriptable Object

What you will get from this page: Tips for how to keep your game code easy to change and debug by architecting it with Scriptable Objects.

These tips come from Ryan Hipple, principal engineer at Schell Games, who has advanced experience using Scriptable Objects to architect games. You can watch Ryan’s Unite talk on Scriptable Objects here; we also recommend you see Unity engineer Richard Fine’s session for a great introduction to Scriptable Objects. Thank you Ryan!

Читайте также:  Способы отказа от сигарет

ScriptableObject is a serializable Unity class that allows you to store large quantities of shared data independent from script instances. Using ScriptableObjects makes it easier to manage changes and debugging. You can build in a level of flexible communication between the different systems in your game, so that it’s more manageable to change and adapt them throughout production, as well as reuse components.

Используйте модульный подход:

  • старайтесь не создавать системы, напрямую зависящие друг от друга. Например, система инвентаря должна иметь канал связи с другими системами в игре, но без жесткой привязки, потому что это усложняет перекомпоновку систем и изменение их взаимосвязей.
  • Создавайте сцены с нуля, избегайте элементов, которые переходят из одной сцены в другую. Загрузка каждой новой сцены должна происходить заново. Это позволяет без грубых маневров создавать сцены, уникальные по своей природе, непохожие одна на другую.
  • Настраивайте префабы так, чтобы они могли работать самостоятельно. Каждый добавленный в сцену префаб должен по возможности иметь как можно более законченную функциональность. Это помогает контролировать кодовую базу в большой команде, где сцены представляют собой список префабов, а префабы самостоятельны в своих функциях. Таким образом, большая часть проверок будет сосредоточена на уровне префабов, что снижает число конфликтов в сцене.
  • Старайтесь делать так, чтобы каждый компонент занимался решением одной задачи. Это облегчит создание нового контента путем сочетания уже готовых компонентов.

Упрощайте изменение и редактирование элементов:

  • сделайте алгоритмы игры информационно-ориентированными настолько, насколько это возможно. Проектируя игровые системы как механизмы, использующие данные как инструкции, вы сможете вносить изменения в игру в любое время, даже во время ее работы.
  • Чем выше степень модульности и компонентности архитектуры игры, тем легче она поддается изменениям, особенно руками художников и дизайнеров. Если дизайнеры смогут собрать игру воедино, не обращаясь за какими-то особыми функциями, в основном благодаря тому, что каждый компонент выполняет только одну задачу, то они смогут сочетать эти компоненты самыми разными способами, реализуя различные варианты игрового процесса и механики. Райан говорит, что большая часть классных особенностей игр, над которыми работала его команда, появилась благодаря этому подходу, который он называет «эмерджентной архитектурой».
  • Очень важно, чтобы команда могла вносить изменения во время работы игры. Чем легче работающая игра поддается изменению, тем легче ее балансировать и настраивать значения, а возможность сохранять рабочее состояние так, как это умеют объекты Scriptable Object, — это очень удобно.

Упрощайте отладку:

на самом деле это кит-помощник для первых двух. Чем выше модульность вашей игры, тем легче тестировать каждый из ее элементов по отдельности. Чем легче игра поддается изменению, чем больше в ней элементов, поддающихся контролю в окне Inspector, тем легче будет ее отладка. Сделайте так, чтобы состояние отладки можно было просматривать в окне Inspector, и никогда не помечайте функцию как завершенную, пока не выработаете план по ее отладке.

Один из самых простых вариантов архитектуры на основе ScriptableObjects — это изолированная переменная в виде ассета. Ниже приведен пример FloatVariable, который можно легко расширить до любого сериализуемого типа.

Любой сотрудник вашей студии, независимо от уровня знаний, сможет объявить новую игровую переменную, создав новый ассет FloatVariable. Любой класс MonoBehaviour или ScriptableObject может использовать общедоступный ассет FloatVariable вместо общедоступной переменной с плавающей запятой для ссылки на новое общее значение.

И даже лучше — если один MonoBehaviour изменит значение FloatVariable, то остальные MonoBehaviour будут в курсе этого изменения. Это — основа слоя коммуникации между системами, которым не нужно ссылаться друг на друга.

Источник

Оцените статью
Разные способы