Skip to content

References

Daniel Everland edited this page Oct 23, 2018 · 10 revisions

Introduction

References are how we expose fields in MonoBehaviour scripts that allow us to assign a variable ScriptableObject. They're wrapped in a separate class because you can also choose not to use a ScriptableObject at all, and instead write a constant value in the inspector.

This is the default view, which allows us to assign a Variable.

You can click on the icon to the left of the field to change state.

"Use Constant" allows us to assign a value directly.

Script Reference

To create a Reference field in your MonoBehaviour script, simply declare it like you would any other field

public BoolReference boolValue;

Or use the [SerializeField] attribute if it's not public

[SerializeField]
private BoolReference boolValue;

You don't have to care whether the Reference is using a constant or a variable, simply reference the Value property

T Value { get; set; }

FAQ

1. Why does the reference not have an implicit operator so you don't have to reference its value directly?

It's true that having the implicit operator would be nice for cases like this

FloatReference reference;
float value;

value = reference;

That wouldn't cause any issues what so ever, and looks nicer than specifically referencing the value property. Consider the following though, it's a common thing you'll encounter without even thinking about it

FloatReference maxHealth;
FloatReference currentHealth;

//We want to start off by ensuring currentHealth is set to maxHealth,
    //so we do the following
currentHealth = maxHealth;

Looks harmless right? Thing is, the reference is an object. We didn't assign any values in the above snippet, instead we changed our currentHealth variable to reference maxHealth instead. Not only did we fail to set the value properly, we caused another bug that won't throw any exceptions. So that's why there's no conversion.

Clone this wiki locally