A little but easy and handy solution to inject dependencies in the Unity-Way (Code & Editor via ScriptableObjects)
- Mark any of your MonoBehaviour with
[ReferenceAutoGeneration]
attribute - After project compilation, add a fresh generated script called
YourClassNameRefSetter
to GameObject which contains yourMonoBehaviour
- Put to the
Scriptable
field your fresh generated asset fromAssets/Data/References/
folder. - The Generated scriptable asset holds an instance of an object.
- To use that instance you need to reference the asset in the way as you always reference assets
via
[SerializedField]
or just mark it aspublic
in yourMonoBehaviour
An example of usage here
When you don't need all the power that Zenject provides, when you have not too many reference-depepending scripts, but you want a simple way to handle dependency injection with some benefits.
- You can create multiple assets by duplicate one of them, doing this you can hold a multiple instances of needed type of a class.
For example you have few characters which needs to be referenced somewhere else, then you can markCharacter
class with the[ReferenceAutoGeneration]
attribute, duplicate your generated asset, rename it and use this assets independently to link to your characters. - It also works for tests in the same way.
- Using this you don't need to hardcode references, using Singletone/ServiceLocator, or doing any other tricky ways to achieve some sort of dependency injection.