Scriptable Objects are an immensely powerful yet often underutilized feature of Unity. Learn how to get the most out of this versatile data structure and build more extensible systems and data patterns. At Schell Games, we have used the Scriptable Object for everything from a hierarchical state machine, to an event system, to a method of cross scene communication. Come hear about our specific examples that push this data type to the limit. In learning about our Scriptable Object usage, you will get some extra knowledge on Unity's serialization mechanics and a ton of editor scripting tips and examples.
20. Solutions
Reduce need for global managers
Inversion of Control
Example: Dependency Injection
Objects are given dependencies
Single responsibility principle
25. Float Reference
[Serializable]
public class FloatReference
{
public bool UseConstant = true;
public float ConstantValue;
public FloatVariable Variable;
public float Value
{
get { return UseConstant ? ConstantValue :
Variable.Value; }
}
}
26. Float Variable
public class DumbEnemy : MonoBehaviour
{
public FloatVariable MaxHP;
public FloatVariable MoveSpeed;
}
public class DumbEnemy : MonoBehaviour
{
public FloatReference MaxHP;
public FloatReference MoveSpeed;
}
36. Making Our Own Events
Data driven
Designer authorable
Debuggable
37. Making Our Own Events
[CreateAssetMenu]
public class GameEvent : ScriptableObject
{
private List<GameEventListener> listeners =
new List<GameEventListener>();
public void Raise()
{
for(int i = listeners.Count -1; i >= 0; i--)
listeners[i].OnEventRaised();
}
public void RegisterListener(GameEventListener listener) ...
public void UnregisterListener(GameEventListener listener) ...
}
38. Making Our Own Events
public class GameEventListener : MonoBehaviour
{
public GameEvent Event;
public UnityEvent Response;
private void OnEnable()
{ Event.RegisterListener(this); }
private void OnDisable()
{ Event.UnregisterListener(this); }
public void OnEventRaised()
{ Response.Invoke(); }
}
43. Runtime Sets
Keep track of a list of objects in the scene
Avoid race conditions
More flexible than Unity tags, singleton
44. Runtime Sets
public abstract class RuntimeSet<T> : ScriptableObject
{
public List<T> Items = new List<T>();
public void Add(T t)
{
if (!Items.Contains(t)) Items.Add(t);
}
public void Remove(T t)
{
if (Items.Contains(t)) Items.Remove(t);
}
}
50. Generic Systems
System is ScriptableObject Asset in project
Reference directly with inspector
No code lookup
No scene-only references
Like AudioMixer / AudioMixerGroup