-
-
Save mikecann/56db29b1ac284578f2a9 to your computer and use it in GitHub Desktop.
AutoWire Notes and Thoughts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// --- AutoWire --- | |
// Service Locator pattern is inferior to DI, but that is what we are stuck with in Unity, so lets make our life easier | |
// | |
// Notes: | |
// 1) any persistent state should be a component or belong to a component (no models, services in thin air) | |
// | |
public class Enemy : AutoWire | |
{ | |
[Locate] | |
public Transform { get; set; } // Will find the component on this gameobject | |
[Locate] | |
public EnemiesManager { get; set; } // wont find the component so will look into AutoWire cache and pull out an instance, | |
// failing that it will do this.FindComponentInParent, | |
// failing that it will use GameObject.FindObjectOfType | |
[Locate] | |
public INotificaitonService { get; get; } // will look into the AutoWire cache for a mapping of this interface | |
// Illegal because AutoWire declares Awake as private | |
void Awake() | |
{ | |
} | |
// If we need to so something in awake use this instead | |
override protected void OnAwake() | |
{ | |
} | |
} | |
// This is a class purely for convenience, you could just do AutoWire.WireUp(this); in your own monobehaviour awake | |
// and thus not need to extend this class at all | |
public class AutoWire : MonoBehaviour | |
{ | |
private void Awake() | |
{ | |
AutoWire.WireUp(this); | |
OnAwake(); | |
} | |
virtual protected void OnAwake() {} | |
} | |
// When AutoWire locates this class for something else it will automatically be put into the cache | |
[AutowireCache] | |
public class EnemiesManager : MonoBehaviour | |
{ | |
} | |
// Here we bootstrap the game and use Edit > Project Settings > Script Execution Order to ensure that its always loaded first | |
public class Bootstrap | |
{ | |
public GameObject managers; | |
void Awake() | |
{ | |
// Whenever the locator is asked for INotificaitonService it will look for AndroidNotificationService instead | |
AutoWire.Map<INotificaitonService>().To<AndroidNotificationService>(); | |
// Will get all the components from the managers object and cache them immediately | |
// so AutoWire doesnt have to go looking for them once they are first requested | |
AutoWire.CacheAllComponentsIn(managers); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment