SlideShare a Scribd company logo
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
Ian Dundore

LeadDeveloperRelationsEngineer,Unity
Scriptable Objects

WhatTheyAre&WhyToUseThem
Scriptable Objects?
• “A class, derived from Unity’s Object class, whose references and fields
can be serialized.”
• That statement is deceptively simple.
Well, what’s a MonoBehaviour?
• It’s a script.
• It receives callbacks from Unity.
• At runtime, it is attached to GameObjects.
• Its data is saved into Scenes and Prefabs.
• Serialization support; can be easily viewed in the Inspector.
Okay, what’s a ScriptableObject?
• It’s a script.
• It doesn’t receive (most) callbacks from Unity.
• At runtime, it is not attached to any specific GameObject.
• Each different instance can be saved to its own file.
• Serialization support; can be easily viewed in the Inspector.
It’s all about the files.
• MonoBehaviours are always serialized alongside other objects
• The GameObject to which they’re attached
• That GameObject’s Transform
• … plus all other Components & MonoBehaviours on the GameObject
• ScriptableObjects can always be saved into their own unique file.
• This is makes version control systems much easier to use.
Shared Data should not be duplicated
• Consider a MonoBehaviour that runs an
NPC’s health.
• Determines current & max health.
• Changes AI behavior when health is low.
• Might look like this
public class NPCHealth : MonoBehaviour
{
[Range(10, 100)]
public int maxHealth;
[Range(10, 100)]
public int healthThreshold;
public NPCAIStateEnum goodHealthAi;
public NPCAIStateEnum lowHealthAi;
[System.NonSerialized]
public int currentHealth;
}
Problems
• Changing any NPC in a Scene or Prefab?
• Tell everyone else not to change that scene or prefab!
• Want to change all NPCs of some type?
• Change the prefab (see above).
• Change every instance in every Scene.
• Someone mistakenly edits MaxHealth or HealthThreshold somewhere?
• Write complex content-checking tools or hope QA catches it.
public class NPCHealthV2 : MonoBehaviour
{
public NPCHealthConfig config;
[System.NonSerialized]
public int currentHealth;
}
[CreateAssetMenu(menuName = "Content/Health Config")]
public class NPCHealthConfig : ScriptableObject
{
[Range(10, 100)]
public int MaxHealth;
[Range(10, 100)]
public int HealthThreshold;
public NPCAIStateEnum GoodHealthAi;
public NPCAIStateEnum LowHealthAi;
}
[CreateAssetMenu] ?
• Adds this to your “Create” menu:
Use Case #1: Shared Data Container
• ScriptableObject looks like this
• MonoBehaviour looks like this
Benefits
• Clean separation of concerns.
• Changing the Health Config changes zero other files.
• Make changes to all my Cool NPCs in one place.
• Optional: Make a custom Property Drawer for NPCHealthConfig
• Can show the ScriptableObject’s data inline.
• Makes designers’ lives easier.
Potential benefit
• Editing ScriptableObject instances during play mode?
• No problem!
• Can be good — let designers iterate while in play mode.
• Can be bad — don’t forget to revert unwanted changes!
Extra bonus
• Your scenes and prefabs now save & load faster.
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
Unity serializes everything
• When saving Scenes & Prefabs, Unity serializes everything inside them.
• Every Component.
• Every GameObject.
• Every public field.
• No duplicate data checking.
• No compression.
More data saved = slower reads/writes
• Disk I/O is one of the slowest operations on a computer.
• Yes, even in today’s world of SSDs.
• A reference to a ScriptableObject is just one small property.
• As the size of the duplicated data grows, the difference grows quickly.
Quick API Reminder
Creating ScriptableObjects
• Make new instances:
• ScriptableObject.CreateInstance<MyScriptableObjectClass>();
• Works both at runtime and in the Editor.
• Save ScriptableObjects to files:
• New asset file: AssetDatabase.CreateAsset();
• Existing asset file: AssetDatabase.AddObjectToFile();
• Use the [CreateAssetMenu] attribute, like before.
• (Unity Editor only.)
ScriptableObject callbacks
• OnEnable
• Called when the ScriptableObject is instantiated/loaded.
• Executes during ScriptableObject.CreateInstance() call.
• Also called in the Editor after script recompilation.
ScriptableObject callbacks (2)
• OnDestroy
• Called right before the ScriptableObject is destroyed.
• Executes during explicit Object.Destroy() calls, after OnDisable.

• OnDisable
• Called when the ScriptableObject is about to be destroyed.
• Executes during explicit Object.Destroy() calls, before OnDestroy.
• Executed just before Object is garbage-collected!
• Also called in the Editor before script recompilation.
ScriptableObject lifecycle
• Created and loaded just like other assets, such as Textures & AudioClips.
• Kept alive just like other assets.
• Will eventually get unloaded:
• Via Object.Destroy or Object.DestroyImmediate
• Or, when there are no references to it and Asset GC runs
• e.g. Resources.UnloadUnusedAssets or scene changes
Warning! Unity is not a C# Engine.
• ScriptableObjects, like other UnityEngine.Object classes, lead a dual life.
• C++ side manages serialization, identity (InstanceID), etc.
• C# side provides an API to you, the developer.
Native Object
(Serialization, InstanceID)
C# Object
(Your Code)
Native Object
(Serialization, InstanceID)
C# Object
(Your Code)
C# Reference
A Wild Reference Appears!
Native Object
(Serialization, InstanceID)
C# Object
(Your Code)
C# Reference
After Destroy()
X
Common Scenarios
Plain Data Container
• We saw this earlier.
• Great way to hold design data, or other authored data.
• For example, use it to save your App Store keys.
• Bake data tables in expensive formats down to ScriptableObjects.
• Convert that JSON blob or XML file during your build!
Friendly, Easy-to-Extend Enumerations
• Use different instances of empty ScriptableObjects to represent distinct
values of the same type.
• Basically an enum, but turns into content.
• Consider, for example, an RPG Item…
class GameItem: ScriptableObject {
public Sprite icon;
public GameItemSlot slot;
public void OnEquip(GameCharacter c) { … }
public void OnRemove(GameCharacter c) { … }
}
class GameItemSlot: ScriptableObject {}
It’s easy.
• Slots are just content, like everything else.
• Designers can add new values with no code changes.
Adding data to existing content is simple.
• Can always add some fields to the GameItemSlot class.
• Maybe we want to add some types of items the user can’t equip.
• Just add a bool isEquippable flag to existing GameItemSlot class
Let’s add behavior!
class GameItem: ScriptableObject {
public Sprite icon;
public GameItemSlot slot;
public GameItemEffect[] effects;
public void OnEquip(GameCharacter c) {
// Apply effects here…?
}
public void OnRemove(GameCharacter c) {
// Remove effects here…?
}
}
class GameItemEffect: ScriptableObject {
public GameCharacterStat stat;
public int statChange;
}
Should GameItemEffect just carry data?
• What if designers want to do something other than just add stats?
• Every effect type’s code has to go into GameItem.OnEquip
• But ScriptableObjects are just classes…
• Why not embed the logic in the GameItemEffect class itself?
abstract class GameItemEffect: ScriptableObject {
public abstract void OnEquip(GameCharacter c);
public abstract void OnRemove(GameCharacter c);
}
class GameItemEffectAddStat: GameItemEffect {
public GameStat stat;
public int amountToAdd;
public override void OnEquip(GameCharacter c) {
c.AddStat(statToChange, amountToAdd);
}
public override void OnRemove(GameCharacter c) {
c.AddStat(statToChange, -1 * amountToAdd);
}
}
class GameItemEffectTransferStat: GameItemEffect {
public GameStat statToDecrease;
public GameState statToIncrease;
public int amountToTransfer;
public override void OnEquip(GameCharacter c) {
c.AddStat(statToReduce, -1 * amountToAdd);
c.AddStat(statToIncrease, amountToTransfer);
}
public override void OnRemove(GameCharacter c) {
c.AddStat(statToReduce, amountToAdd);
c.AddStat(statToIncrease, -1 * amountToTransfer);
}
}
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
class GameItem: ScriptableObject {
public Sprite icon;
public GameItemSlot slot;
public GameItemEffect[] effects;
public bool OnEquip(GameCharacter c) {
for(int i = 0; i < effects.Length; ++i) {
effects[i].OnEquip(c);
}
}
public bool OnRemove(GameCharacter c) { … }
}
Nice editor workflow!
Serializable game logic!
• Each effect now carries only the data it needs.
• Applies its operations through a simple (testable?) interface.
• Designers can drag & drop everything.
• Add new logic without refactoring existing content.
Serializable… delegates?
• Consider a simple enemy AI, with a few different types of behavior.
• Could just pack this all into a MonoBehaviour, use an enum or variable to
determine AI type.
• Or…
class GameNPC: MonoBehaviour {
public GameAI brain;
void Update() {
brain.Update(this);
}
}
abstract class GameAI: ScriptableObject {
abstract void Update(GameNPC me);
}
class PassiveAI: GameAI { … }
class AggressiveAI: GameAI { … }
class FriendlyAI: GameAI { … }
Easier to implement, extend & test
• Imagine our designers, later on, wanted to add an AI that would attack you
when you attacked one of its friends.
• With this model:
• Add a new AI type
• Allow the designer to define an array of friends.
• When one is attacked, set the current AI module to an AggressiveAI.
• No changes to other code or content needed!
So in sum…
ScriptableObjects are great!
• Use them to make version control easier.
• Use them to speed up data loading.
• Use them to give your designers an easier workflow.
• Use them to configure your logic via content.
Thank you!

More Related Content

PPTX
猫でも分かる UE4のAnimation Blueprintの運用について
エピック・ゲームズ・ジャパン Epic Games Japan
 
PPTX
C++コードはいらない!UE4で作るお手軽マルチプレイ ネットワークゲームについて
Masahiko Nakamura
 
PDF
UniTask入門
torisoup
 
PPTX
UE4 MultiPlayer Online Deep Dive 基礎編2 -Traveling- (historia様ご講演) #ue4dd
エピック・ゲームズ・ジャパン Epic Games Japan
 
PDF
UE4とUnrealC++について
Masahiko Nakamura
 
PDF
バイキング流UE4活用術 ~BPとお別れするまでの18ヶ月~
エピック・ゲームズ・ジャパン Epic Games Japan
 
PDF
UE4におけるエフェクトの為のエンジン改造事例
エピック・ゲームズ・ジャパン Epic Games Japan
 
猫でも分かる UE4のAnimation Blueprintの運用について
エピック・ゲームズ・ジャパン Epic Games Japan
 
C++コードはいらない!UE4で作るお手軽マルチプレイ ネットワークゲームについて
Masahiko Nakamura
 
UniTask入門
torisoup
 
UE4 MultiPlayer Online Deep Dive 基礎編2 -Traveling- (historia様ご講演) #ue4dd
エピック・ゲームズ・ジャパン Epic Games Japan
 
UE4とUnrealC++について
Masahiko Nakamura
 
バイキング流UE4活用術 ~BPとお別れするまでの18ヶ月~
エピック・ゲームズ・ジャパン Epic Games Japan
 
UE4におけるエフェクトの為のエンジン改造事例
エピック・ゲームズ・ジャパン Epic Games Japan
 

What's hot (20)

PDF
UE4 アセットロード周り-アセット参照調査-
com044
 
PDF
UE4でマルチプレイヤーゲームを作ろう
エピック・ゲームズ・ジャパン Epic Games Japan
 
PDF
UE4.14.0 Forward Shadingのエンジン改造でセルシェードやってみた
com044
 
PPTX
はじめてのAI~ 愛のあるAIを作ろう
Masahiko Nakamura
 
PDF
【Unity】Scriptable object 入門と活用例
Unity Technologies Japan K.K.
 
PPTX
ぷちコン作品を4日で作った話
Tomioka Yusei
 
PDF
Unreal Engine 4.27 ノンゲーム向け新機能まとめ
エピック・ゲームズ・ジャパン Epic Games Japan
 
PPTX
[4.20版] UE4におけるLoadingとGCのProfilingと最適化手法
エピック・ゲームズ・ジャパン Epic Games Japan
 
DOCX
UE4でPerforceと連携するための手順
エピック・ゲームズ・ジャパン Epic Games Japan
 
PDF
60fpsアクションを実現する秘訣を伝授 基礎編
エピック・ゲームズ・ジャパン Epic Games Japan
 
PDF
オンラインで同期した100体の巨大生物から地球を衛る方法 UNREAL FEST EXTREME 2021 SUMMER
エピック・ゲームズ・ジャパン Epic Games Japan
 
PDF
猫でも分かる UE4の新しいサンプル「Action RPG」について
エピック・ゲームズ・ジャパン Epic Games Japan
 
PDF
新しいエフェクトツール、Niagaraを楽しもう! ~Niagara作例のブレイクダウン~
エピック・ゲームズ・ジャパン Epic Games Japan
 
PDF
メカアクションゲーム『DAEMON X MACHINA』 信念と血と鋼鉄の開発事例
エピック・ゲームズ・ジャパン Epic Games Japan
 
PDF
Deep Dive async/await in Unity with UniTask(UniRx.Async)
Yoshifumi Kawai
 
PPTX
[CEDEC2018] UE4で多数のキャラクターを生かすためのテクニック
エピック・ゲームズ・ジャパン Epic Games Japan
 
PDF
【Unite Tokyo 2019】バンダイナムコスタジオ流Unityの使い方
UnityTechnologiesJapan002
 
PDF
Editor Utility Widgetで色々便利にしてみた。
IndieusGames
 
PDF
UE4における大規模背景制作事例(コリジョン編)
エピック・ゲームズ・ジャパン Epic Games Japan
 
PDF
ヒストリア HelixCore(Perforce) 運用レギュレーションドキュメント
historia_Inc
 
UE4 アセットロード周り-アセット参照調査-
com044
 
UE4でマルチプレイヤーゲームを作ろう
エピック・ゲームズ・ジャパン Epic Games Japan
 
UE4.14.0 Forward Shadingのエンジン改造でセルシェードやってみた
com044
 
はじめてのAI~ 愛のあるAIを作ろう
Masahiko Nakamura
 
【Unity】Scriptable object 入門と活用例
Unity Technologies Japan K.K.
 
ぷちコン作品を4日で作った話
Tomioka Yusei
 
Unreal Engine 4.27 ノンゲーム向け新機能まとめ
エピック・ゲームズ・ジャパン Epic Games Japan
 
[4.20版] UE4におけるLoadingとGCのProfilingと最適化手法
エピック・ゲームズ・ジャパン Epic Games Japan
 
UE4でPerforceと連携するための手順
エピック・ゲームズ・ジャパン Epic Games Japan
 
60fpsアクションを実現する秘訣を伝授 基礎編
エピック・ゲームズ・ジャパン Epic Games Japan
 
オンラインで同期した100体の巨大生物から地球を衛る方法 UNREAL FEST EXTREME 2021 SUMMER
エピック・ゲームズ・ジャパン Epic Games Japan
 
猫でも分かる UE4の新しいサンプル「Action RPG」について
エピック・ゲームズ・ジャパン Epic Games Japan
 
新しいエフェクトツール、Niagaraを楽しもう! ~Niagara作例のブレイクダウン~
エピック・ゲームズ・ジャパン Epic Games Japan
 
メカアクションゲーム『DAEMON X MACHINA』 信念と血と鋼鉄の開発事例
エピック・ゲームズ・ジャパン Epic Games Japan
 
Deep Dive async/await in Unity with UniTask(UniRx.Async)
Yoshifumi Kawai
 
[CEDEC2018] UE4で多数のキャラクターを生かすためのテクニック
エピック・ゲームズ・ジャパン Epic Games Japan
 
【Unite Tokyo 2019】バンダイナムコスタジオ流Unityの使い方
UnityTechnologiesJapan002
 
Editor Utility Widgetで色々便利にしてみた。
IndieusGames
 
UE4における大規模背景制作事例(コリジョン編)
エピック・ゲームズ・ジャパン Epic Games Japan
 
ヒストリア HelixCore(Perforce) 運用レギュレーションドキュメント
historia_Inc
 
Ad

Viewers also liked (14)

PDF
【Unite 2017 Tokyo】Nintendo Switch™ 本体同時発売必達、家庭用向けRPG「いけにえと雪のセツナ」開発の裏側
Unity Technologies Japan K.K.
 
PPT
実行時のために最適なデータ構造を作成しよう
Hiroki Omae
 
PDF
Unity5.3で知識が止まっている人向けのUnity2017.2に合わせたエディター拡張アップデート
Keigo Ando
 
PPTX
Unityでlinqを使おう
Yuuki Takada
 
PPTX
良くわかるMeta
daichi horio
 
PDF
Gtmf2011 2011.06.07 slideshare
Hiroki Omae
 
PPTX
ゲームエンジニアのためのデータベース設計
sairoutine
 
PDF
【Unite 2017 Tokyo】VRで探り,活用する,人の知覚の仕組み
Unite2017Tokyo
 
PDF
ソーシャルゲームのためのデータベース設計
Yoshinori Matsunobu
 
PDF
【Unite 2017 Tokyo】もっと気軽に、動的なコンテンツ配信を ~アセットバンドルの未来と開発ロードマップ
Unite2017Tokyo
 
PDF
【Unite 2017 Tokyo】セルシェーダーを使用した3Dキャラアプリの開発事例
Unity Technologies Japan K.K.
 
PDF
LINQ in Unity
Yoshifumi Kawai
 
PDF
UniRx - Reactive Extensions for Unity
Yoshifumi Kawai
 
PDF
Binary Reading in C#
Yoshifumi Kawai
 
【Unite 2017 Tokyo】Nintendo Switch™ 本体同時発売必達、家庭用向けRPG「いけにえと雪のセツナ」開発の裏側
Unity Technologies Japan K.K.
 
実行時のために最適なデータ構造を作成しよう
Hiroki Omae
 
Unity5.3で知識が止まっている人向けのUnity2017.2に合わせたエディター拡張アップデート
Keigo Ando
 
Unityでlinqを使おう
Yuuki Takada
 
良くわかるMeta
daichi horio
 
Gtmf2011 2011.06.07 slideshare
Hiroki Omae
 
ゲームエンジニアのためのデータベース設計
sairoutine
 
【Unite 2017 Tokyo】VRで探り,活用する,人の知覚の仕組み
Unite2017Tokyo
 
ソーシャルゲームのためのデータベース設計
Yoshinori Matsunobu
 
【Unite 2017 Tokyo】もっと気軽に、動的なコンテンツ配信を ~アセットバンドルの未来と開発ロードマップ
Unite2017Tokyo
 
【Unite 2017 Tokyo】セルシェーダーを使用した3Dキャラアプリの開発事例
Unity Technologies Japan K.K.
 
LINQ in Unity
Yoshifumi Kawai
 
UniRx - Reactive Extensions for Unity
Yoshifumi Kawai
 
Binary Reading in C#
Yoshifumi Kawai
 
Ad

Similar to 【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう (20)

PPTX
Soc research
Bryan Duggan
 
PDF
Rapid prototyping with ScriptableObjects
Giorgio Pomettini
 
PDF
iPhone dev intro
Vonbo
 
PDF
Beginning to iPhone development
Vonbo
 
KEY
Artdm170 Week5 Intro To Flash
Gilbert Guerrero
 
PDF
FI MUNI 2012 - iOS Basics
Petr Dvorak
 
PDF
The Hack Spectrum: Tips, Tricks, and Hacks for Unity
Ryan Hipple
 
PPTX
Getting started with jQuery
Gill Cleeren
 
KEY
ARTDM 170, Week 5: Intro To Flash
Gilbert Guerrero
 
PDF
MFF UK - Introduction to iOS
Petr Dvorak
 
PPTX
We Love Performance! How Tic Toc Games Uses ECS in Mobile Puzzle Games
Unity Technologies
 
PPTX
constructocvbcvbcvbcvbr-Destructor (1).pptx
WrushabhShirsat3
 
PPT
Lecture 3-ARC
Ziku Spartan
 
PPTX
Real World MVC
James Johnson
 
PPTX
Optimizing mobile applications - Ian Dundore, Mark Harkness
ozlael ozlael
 
PDF
Look Again at the ZCA
mikerhodes
 
PDF
iOS Automation Primitives
Synack
 
PDF
Owasp orlando, april 13, 2016
Mikhail Sosonkin
 
PDF
Lotusphere 2012 Speedgeeking - jQuery & Domino, a RAD Combination
Sean Burgess
 
Soc research
Bryan Duggan
 
Rapid prototyping with ScriptableObjects
Giorgio Pomettini
 
iPhone dev intro
Vonbo
 
Beginning to iPhone development
Vonbo
 
Artdm170 Week5 Intro To Flash
Gilbert Guerrero
 
FI MUNI 2012 - iOS Basics
Petr Dvorak
 
The Hack Spectrum: Tips, Tricks, and Hacks for Unity
Ryan Hipple
 
Getting started with jQuery
Gill Cleeren
 
ARTDM 170, Week 5: Intro To Flash
Gilbert Guerrero
 
MFF UK - Introduction to iOS
Petr Dvorak
 
We Love Performance! How Tic Toc Games Uses ECS in Mobile Puzzle Games
Unity Technologies
 
constructocvbcvbcvbcvbr-Destructor (1).pptx
WrushabhShirsat3
 
Lecture 3-ARC
Ziku Spartan
 
Real World MVC
James Johnson
 
Optimizing mobile applications - Ian Dundore, Mark Harkness
ozlael ozlael
 
Look Again at the ZCA
mikerhodes
 
iOS Automation Primitives
Synack
 
Owasp orlando, april 13, 2016
Mikhail Sosonkin
 
Lotusphere 2012 Speedgeeking - jQuery & Domino, a RAD Combination
Sean Burgess
 

More from Unity Technologies Japan K.K. (20)

PDF
建築革命、更に更に進化!便利さ向上【Unity Reflect ver 3.0 】
Unity Technologies Japan K.K.
 
PDF
UnityのクラッシュをBacktraceでデバッグしよう!
Unity Technologies Japan K.K.
 
PDF
Unityで始めるバーチャルプロダクション
Unity Technologies Japan K.K.
 
PDF
ビジュアルスクリプティング (旧:Bolt) で始めるUnity入門3日目 ゲームをカスタマイズしよう
Unity Technologies Japan K.K.
 
PDF
ビジュアルスクリプティングで始めるUnity入門2日目 ゴールとスコアの仕組み - Unityステーション
Unity Technologies Japan K.K.
 
PDF
ビジュアルスクリプティングで始めるUnity入門1日目 プレイヤーを動かそう
Unity Technologies Japan K.K.
 
PDF
PlasticSCMの活用テクニックをハンズオンで一緒に学ぼう!
Unity Technologies Japan K.K.
 
PDF
点群を使いこなせ! 可視化なんて当たり前、xRと点群を組み合わせたUnityの世界 【Interact , Stipple】
Unity Technologies Japan K.K.
 
PDF
Unity教える先生方注目!ティーチャートレーニングデイを体験しよう
Unity Technologies Japan K.K.
 
PDF
「原神」におけるコンソールプラットフォーム開発
Unity Technologies Japan K.K.
 
PDF
FANTASIANの明日使えない特殊テクニック教えます
Unity Technologies Japan K.K.
 
PDF
インディーゲーム開発の現状と未来 2021
Unity Technologies Japan K.K.
 
PDF
建築革命、更に進化!デジタルツイン基盤の真打ち登場【概要編 Unity Reflect ver 2.1 】
Unity Technologies Japan K.K.
 
PDF
Burstを使ってSHA-256のハッシュ計算を高速に行う話
Unity Technologies Japan K.K.
 
PDF
Cinemachineで見下ろし視点のカメラを作る
Unity Technologies Japan K.K.
 
PDF
徹底解説 Unity Reflect【開発編 ver2.0】
Unity Technologies Japan K.K.
 
PDF
徹底解説 Unity Reflect【概要編 ver2.0】
Unity Technologies Japan K.K.
 
PDF
Unityティーチャートレーニングデイ -認定プログラマー編-
Unity Technologies Japan K.K.
 
PDF
Unityティーチャートレーニングデイ -認定3Dアーティスト編-
Unity Technologies Japan K.K.
 
PDF
Unityティーチャートレーニングデイ -認定アソシエイト編-
Unity Technologies Japan K.K.
 
建築革命、更に更に進化!便利さ向上【Unity Reflect ver 3.0 】
Unity Technologies Japan K.K.
 
UnityのクラッシュをBacktraceでデバッグしよう!
Unity Technologies Japan K.K.
 
Unityで始めるバーチャルプロダクション
Unity Technologies Japan K.K.
 
ビジュアルスクリプティング (旧:Bolt) で始めるUnity入門3日目 ゲームをカスタマイズしよう
Unity Technologies Japan K.K.
 
ビジュアルスクリプティングで始めるUnity入門2日目 ゴールとスコアの仕組み - Unityステーション
Unity Technologies Japan K.K.
 
ビジュアルスクリプティングで始めるUnity入門1日目 プレイヤーを動かそう
Unity Technologies Japan K.K.
 
PlasticSCMの活用テクニックをハンズオンで一緒に学ぼう!
Unity Technologies Japan K.K.
 
点群を使いこなせ! 可視化なんて当たり前、xRと点群を組み合わせたUnityの世界 【Interact , Stipple】
Unity Technologies Japan K.K.
 
Unity教える先生方注目!ティーチャートレーニングデイを体験しよう
Unity Technologies Japan K.K.
 
「原神」におけるコンソールプラットフォーム開発
Unity Technologies Japan K.K.
 
FANTASIANの明日使えない特殊テクニック教えます
Unity Technologies Japan K.K.
 
インディーゲーム開発の現状と未来 2021
Unity Technologies Japan K.K.
 
建築革命、更に進化!デジタルツイン基盤の真打ち登場【概要編 Unity Reflect ver 2.1 】
Unity Technologies Japan K.K.
 
Burstを使ってSHA-256のハッシュ計算を高速に行う話
Unity Technologies Japan K.K.
 
Cinemachineで見下ろし視点のカメラを作る
Unity Technologies Japan K.K.
 
徹底解説 Unity Reflect【開発編 ver2.0】
Unity Technologies Japan K.K.
 
徹底解説 Unity Reflect【概要編 ver2.0】
Unity Technologies Japan K.K.
 
Unityティーチャートレーニングデイ -認定プログラマー編-
Unity Technologies Japan K.K.
 
Unityティーチャートレーニングデイ -認定3Dアーティスト編-
Unity Technologies Japan K.K.
 
Unityティーチャートレーニングデイ -認定アソシエイト編-
Unity Technologies Japan K.K.
 

Recently uploaded (20)

PDF
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
PDF
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
PPTX
Coupa-Overview _Assumptions presentation
annapureddyn
 
PDF
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
PPTX
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
 
PDF
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
PDF
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
PPTX
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
PDF
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
PPTX
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
PDF
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
PDF
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
PDF
REPORT: Heating appliances market in Poland 2024
SPIUG
 
PDF
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
PDF
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
Coupa-Overview _Assumptions presentation
annapureddyn
 
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
 
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
REPORT: Heating appliances market in Poland 2024
SPIUG
 
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 

【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう

  • 4. Scriptable Objects? • “A class, derived from Unity’s Object class, whose references and fields can be serialized.” • That statement is deceptively simple.
  • 5. Well, what’s a MonoBehaviour? • It’s a script. • It receives callbacks from Unity. • At runtime, it is attached to GameObjects. • Its data is saved into Scenes and Prefabs. • Serialization support; can be easily viewed in the Inspector.
  • 6. Okay, what’s a ScriptableObject? • It’s a script. • It doesn’t receive (most) callbacks from Unity. • At runtime, it is not attached to any specific GameObject. • Each different instance can be saved to its own file. • Serialization support; can be easily viewed in the Inspector.
  • 7. It’s all about the files. • MonoBehaviours are always serialized alongside other objects • The GameObject to which they’re attached • That GameObject’s Transform • … plus all other Components & MonoBehaviours on the GameObject • ScriptableObjects can always be saved into their own unique file. • This is makes version control systems much easier to use.
  • 8. Shared Data should not be duplicated • Consider a MonoBehaviour that runs an NPC’s health. • Determines current & max health. • Changes AI behavior when health is low. • Might look like this
  • 9. public class NPCHealth : MonoBehaviour { [Range(10, 100)] public int maxHealth; [Range(10, 100)] public int healthThreshold; public NPCAIStateEnum goodHealthAi; public NPCAIStateEnum lowHealthAi; [System.NonSerialized] public int currentHealth; }
  • 10. Problems • Changing any NPC in a Scene or Prefab? • Tell everyone else not to change that scene or prefab! • Want to change all NPCs of some type? • Change the prefab (see above). • Change every instance in every Scene. • Someone mistakenly edits MaxHealth or HealthThreshold somewhere? • Write complex content-checking tools or hope QA catches it.
  • 11. public class NPCHealthV2 : MonoBehaviour { public NPCHealthConfig config; [System.NonSerialized] public int currentHealth; }
  • 12. [CreateAssetMenu(menuName = "Content/Health Config")] public class NPCHealthConfig : ScriptableObject { [Range(10, 100)] public int MaxHealth; [Range(10, 100)] public int HealthThreshold; public NPCAIStateEnum GoodHealthAi; public NPCAIStateEnum LowHealthAi; }
  • 13. [CreateAssetMenu] ? • Adds this to your “Create” menu:
  • 14. Use Case #1: Shared Data Container • ScriptableObject looks like this • MonoBehaviour looks like this
  • 15. Benefits • Clean separation of concerns. • Changing the Health Config changes zero other files. • Make changes to all my Cool NPCs in one place. • Optional: Make a custom Property Drawer for NPCHealthConfig • Can show the ScriptableObject’s data inline. • Makes designers’ lives easier.
  • 16. Potential benefit • Editing ScriptableObject instances during play mode? • No problem! • Can be good — let designers iterate while in play mode. • Can be bad — don’t forget to revert unwanted changes!
  • 17. Extra bonus • Your scenes and prefabs now save & load faster.
  • 19. Unity serializes everything • When saving Scenes & Prefabs, Unity serializes everything inside them. • Every Component. • Every GameObject. • Every public field. • No duplicate data checking. • No compression.
  • 20. More data saved = slower reads/writes • Disk I/O is one of the slowest operations on a computer. • Yes, even in today’s world of SSDs. • A reference to a ScriptableObject is just one small property. • As the size of the duplicated data grows, the difference grows quickly.
  • 22. Creating ScriptableObjects • Make new instances: • ScriptableObject.CreateInstance<MyScriptableObjectClass>(); • Works both at runtime and in the Editor. • Save ScriptableObjects to files: • New asset file: AssetDatabase.CreateAsset(); • Existing asset file: AssetDatabase.AddObjectToFile(); • Use the [CreateAssetMenu] attribute, like before. • (Unity Editor only.)
  • 23. ScriptableObject callbacks • OnEnable • Called when the ScriptableObject is instantiated/loaded. • Executes during ScriptableObject.CreateInstance() call. • Also called in the Editor after script recompilation.
  • 24. ScriptableObject callbacks (2) • OnDestroy • Called right before the ScriptableObject is destroyed. • Executes during explicit Object.Destroy() calls, after OnDisable.
 • OnDisable • Called when the ScriptableObject is about to be destroyed. • Executes during explicit Object.Destroy() calls, before OnDestroy. • Executed just before Object is garbage-collected! • Also called in the Editor before script recompilation.
  • 25. ScriptableObject lifecycle • Created and loaded just like other assets, such as Textures & AudioClips. • Kept alive just like other assets. • Will eventually get unloaded: • Via Object.Destroy or Object.DestroyImmediate • Or, when there are no references to it and Asset GC runs • e.g. Resources.UnloadUnusedAssets or scene changes
  • 26. Warning! Unity is not a C# Engine. • ScriptableObjects, like other UnityEngine.Object classes, lead a dual life. • C++ side manages serialization, identity (InstanceID), etc. • C# side provides an API to you, the developer.
  • 28. Native Object (Serialization, InstanceID) C# Object (Your Code) C# Reference A Wild Reference Appears!
  • 29. Native Object (Serialization, InstanceID) C# Object (Your Code) C# Reference After Destroy() X
  • 31. Plain Data Container • We saw this earlier. • Great way to hold design data, or other authored data. • For example, use it to save your App Store keys. • Bake data tables in expensive formats down to ScriptableObjects. • Convert that JSON blob or XML file during your build!
  • 32. Friendly, Easy-to-Extend Enumerations • Use different instances of empty ScriptableObjects to represent distinct values of the same type. • Basically an enum, but turns into content. • Consider, for example, an RPG Item…
  • 33. class GameItem: ScriptableObject { public Sprite icon; public GameItemSlot slot; public void OnEquip(GameCharacter c) { … } public void OnRemove(GameCharacter c) { … } } class GameItemSlot: ScriptableObject {}
  • 34. It’s easy. • Slots are just content, like everything else. • Designers can add new values with no code changes.
  • 35. Adding data to existing content is simple. • Can always add some fields to the GameItemSlot class. • Maybe we want to add some types of items the user can’t equip. • Just add a bool isEquippable flag to existing GameItemSlot class
  • 37. class GameItem: ScriptableObject { public Sprite icon; public GameItemSlot slot; public GameItemEffect[] effects; public void OnEquip(GameCharacter c) { // Apply effects here…? } public void OnRemove(GameCharacter c) { // Remove effects here…? } }
  • 38. class GameItemEffect: ScriptableObject { public GameCharacterStat stat; public int statChange; }
  • 39. Should GameItemEffect just carry data? • What if designers want to do something other than just add stats? • Every effect type’s code has to go into GameItem.OnEquip • But ScriptableObjects are just classes… • Why not embed the logic in the GameItemEffect class itself?
  • 40. abstract class GameItemEffect: ScriptableObject { public abstract void OnEquip(GameCharacter c); public abstract void OnRemove(GameCharacter c); }
  • 41. class GameItemEffectAddStat: GameItemEffect { public GameStat stat; public int amountToAdd; public override void OnEquip(GameCharacter c) { c.AddStat(statToChange, amountToAdd); } public override void OnRemove(GameCharacter c) { c.AddStat(statToChange, -1 * amountToAdd); } }
  • 42. class GameItemEffectTransferStat: GameItemEffect { public GameStat statToDecrease; public GameState statToIncrease; public int amountToTransfer; public override void OnEquip(GameCharacter c) { c.AddStat(statToReduce, -1 * amountToAdd); c.AddStat(statToIncrease, amountToTransfer); } public override void OnRemove(GameCharacter c) { c.AddStat(statToReduce, amountToAdd); c.AddStat(statToIncrease, -1 * amountToTransfer); } }
  • 44. class GameItem: ScriptableObject { public Sprite icon; public GameItemSlot slot; public GameItemEffect[] effects; public bool OnEquip(GameCharacter c) { for(int i = 0; i < effects.Length; ++i) { effects[i].OnEquip(c); } } public bool OnRemove(GameCharacter c) { … } }
  • 46. Serializable game logic! • Each effect now carries only the data it needs. • Applies its operations through a simple (testable?) interface. • Designers can drag & drop everything. • Add new logic without refactoring existing content.
  • 47. Serializable… delegates? • Consider a simple enemy AI, with a few different types of behavior. • Could just pack this all into a MonoBehaviour, use an enum or variable to determine AI type. • Or…
  • 48. class GameNPC: MonoBehaviour { public GameAI brain; void Update() { brain.Update(this); } } abstract class GameAI: ScriptableObject { abstract void Update(GameNPC me); }
  • 49. class PassiveAI: GameAI { … } class AggressiveAI: GameAI { … } class FriendlyAI: GameAI { … }
  • 50. Easier to implement, extend & test • Imagine our designers, later on, wanted to add an AI that would attack you when you attacked one of its friends. • With this model: • Add a new AI type • Allow the designer to define an array of friends. • When one is attacked, set the current AI module to an AggressiveAI. • No changes to other code or content needed!
  • 52. ScriptableObjects are great! • Use them to make version control easier. • Use them to speed up data loading. • Use them to give your designers an easier workflow. • Use them to configure your logic via content.