├── LICENSE ├── LICENSE.meta ├── README.md ├── README.md.meta ├── Scripts.meta ├── Scripts ├── AutoInjectedMonoBehaviour.cs ├── AutoInjectedMonoBehaviour.cs.meta ├── DependencyInjection.asmdef ├── DependencyInjection.asmdef.meta ├── InjectAttribute.cs ├── InjectAttribute.cs.meta ├── Injector.cs └── Injector.cs.meta ├── package.json └── package.json.meta /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Ming-Lun "Allen" Chou 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /LICENSE.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: fd3aeee6640f4ed428c5ba8abfbcfc6d 3 | DefaultImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## A Simple Dependency Injection Utility for Unity 2 | ### (Oops. It's actually a service locator rathern than dependency injection. Will clean up the terms later...) 3 | by **Ming-Lun "Allen" Chou** / [AllenChou.net](http://AllenChou.net) / [@TheAllenChou](http://twitter.com/TheAllenChou) / [Patreon](https://www.patreon.com/TheAllenChou) 4 | 5 | [Installation Guide](https://docs.unity3d.com/Manual/upm-ui-giturl.html) 6 | 7 | ## Usage 8 | 9 | Add the `Inject` attribute to fields of type `GameObject` or `Component`. An additional game object name can be provided to the `Inject` attribute to specify which game object to inject from. If no game object name is provided, the game object of the component will be used. 10 | 11 | Call `Injector.Inject` to inject into fields tagged with the `Inject` attribute. 12 | 13 | ```cs 14 | using UnityEngine; 15 | 16 | using LongBunnyLabs.DependencyInjection; 17 | 18 | public class MyComponent : MonoBehaviour 19 | { 20 | [Inject] private GameObject MyGameObject; 21 | [Inject] private Transform MyTransform; 22 | [Inject] private MeshRenderer MyRenderer; 23 | [Inject("Other")] private GameObject OtherGameObject; 24 | [Inject("Other")] private Transform OtherTransform; 25 | [Inject("Other")] private MeshRenderer OtherRenderer; 26 | 27 | private void Start() 28 | { 29 | Injector.Inject(this); 30 | } 31 | } 32 | ``` 33 | 34 | This is equivalent to: 35 | 36 | ```cs 37 | using UnityEngine; 38 | 39 | public class MyComponent : MonoBehaviour 40 | { 41 | private GameObject MyGameObject; 42 | private Transform MyTransform; 43 | private MeshRenderer MyRenderer; 44 | private GameObject OtherGameObject; 45 | private Transform OtherTransform; 46 | private MeshRenderer OtherRenderer; 47 | 48 | private void Start() 49 | { 50 | MyGameObject = gameObject; 51 | MyTransform = gameObject.GetComponent(); 52 | MyRenderer = gameObject.GetComponent(); 53 | OtherGameObject = GameObject.Find("Other"); 54 | OtherTransform = GameObject.Find("Other").GetComponent(); 55 | OtherRenderer = GameObject.Find("Other").GetComponent(); 56 | } 57 | } 58 | ``` 59 | 60 | You can also inherit your component from `AutoInjectedMonoBehaviour`, whose `Start` method calls `Injector.Inject` so you don't have to. 61 | 62 | ```cs 63 | using UnityEngine; 64 | 65 | using LongBunnyLabs.DependencyInjection; 66 | 67 | public class MyComponent : AutoInjectedMonoBehaviour 68 | { 69 | [Inject] private GameObject Self; 70 | [Inject] private Transform MyTransform; 71 | [Inject] private MeshRenderer MyRenderer; 72 | [Inject("Other")] private GameObject Other; 73 | [Inject("Other")] private Transform TheirTransform; 74 | [Inject("Other")] private MeshRenderer TheirRenderer; 75 | } 76 | ``` 77 | 78 | If you need to override the `Start` method, however, you'd need to remember to call `base.Start`. 79 | 80 | ```cs 81 | using UnityEngine; 82 | 83 | using LongBunnyLabs.DependencyInjection; 84 | 85 | public class MyComponent : AutoInjectedMonoBehaviour 86 | { 87 | [Inject] private GameObject Self; 88 | [Inject] private Transform MyTransform; 89 | [Inject] private MeshRenderer MyRenderer; 90 | [Inject("Other")] private GameObject Other; 91 | [Inject("Other")] private Transform TheirTransform; 92 | [Inject("Other")] private MeshRenderer TheirRenderer; 93 | 94 | protected override void Start() 95 | { 96 | base.Start(); 97 | 98 | // your code here 99 | } 100 | } 101 | ``` 102 | 103 | `Injector.Inject` doesn't have to be called within a `Start` method. You can call it whereever you see fit. 104 | -------------------------------------------------------------------------------- /README.md.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: ac9137967ddb95a4f9128ab6829e48c2 3 | TextScriptImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | -------------------------------------------------------------------------------- /Scripts.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: f83061069fd72194897374da23b716c4 3 | folderAsset: yes 4 | DefaultImporter: 5 | externalObjects: {} 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /Scripts/AutoInjectedMonoBehaviour.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | 3 | namespace LongBunnyLabs.DependencyInjection 4 | { 5 | public class AutoInjectedMonoBehaviour : MonoBehaviour 6 | { 7 | virtual protected void Start() 8 | { 9 | Injector.Inject(this); 10 | } 11 | } 12 | } 13 | 14 | -------------------------------------------------------------------------------- /Scripts/AutoInjectedMonoBehaviour.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 467f56ccc5bed174db6686dbac6f999d 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Scripts/DependencyInjection.asmdef: -------------------------------------------------------------------------------- 1 | { 2 | "name": "LongBunnyLabs.DependencyInjection", 3 | "references": [], 4 | "includePlatforms": [], 5 | "excludePlatforms": [], 6 | "allowUnsafeCode": false, 7 | "overrideReferences": false, 8 | "precompiledReferences": [], 9 | "autoReferenced": true, 10 | "defineConstraints": [], 11 | "versionDefines": [], 12 | "noEngineReferences": false 13 | } -------------------------------------------------------------------------------- /Scripts/DependencyInjection.asmdef.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: d1ad759a4c2234c45b32aea9d024b06d 3 | AssemblyDefinitionImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | -------------------------------------------------------------------------------- /Scripts/InjectAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace LongBunnyLabs.DependencyInjection 4 | { 5 | [AttributeUsage(AttributeTargets.Field, AllowMultiple = false)] 6 | public class InjectAttribute : Attribute 7 | { 8 | public string GameObjectName { get; } = ""; 9 | 10 | public InjectAttribute(string gameObjectName = "") 11 | { 12 | GameObjectName = gameObjectName; 13 | } 14 | } 15 | } 16 | 17 | -------------------------------------------------------------------------------- /Scripts/InjectAttribute.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 717779e0f35ec7b4da71454709288794 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Scripts/Injector.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | 3 | using UnityEngine; 4 | 5 | namespace LongBunnyLabs.DependencyInjection 6 | { 7 | public sealed class Injector 8 | { 9 | public static void Inject(Component component) 10 | { 11 | var componentType = component.GetType(); 12 | var gameObject = component.gameObject; 13 | 14 | var fields = componentType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic); 15 | for (int i = 0; i < fields.Length; ++i) 16 | { 17 | var field = fields[i]; 18 | 19 | var injects = (InjectAttribute[]) field.GetCustomAttributes(typeof(InjectAttribute), true); 20 | if (injects.Length <= 0) 21 | continue; 22 | 23 | bool isComponent = field.FieldType.IsSubclassOf(typeof(Component)); 24 | bool isGameObject = field.FieldType.IsEquivalentTo(typeof(GameObject)); 25 | 26 | if (!isComponent && !isGameObject) 27 | { 28 | Debug.LogWarning($"Dependency Injection: Field '{field.Name}' of component '{componentType.FullName}' is not of valid type 'UnityEngine.Component' nor 'UnityEngine.GameObject'."); 29 | continue; 30 | } 31 | 32 | var inject = injects[0]; 33 | GameObject go = 34 | string.IsNullOrEmpty(inject.GameObjectName) 35 | ? gameObject 36 | : GameObject.Find(inject.GameObjectName); 37 | 38 | if (go == null) 39 | { 40 | Debug.LogWarning($"Dependency Injection: Can't find game object '{inject.GameObjectName}' when injecting field '{field.Name}' of component '{componentType.FullName}'."); 41 | continue; 42 | } 43 | 44 | Object value = go; 45 | if (isComponent) 46 | { 47 | value = go.GetComponent(field.FieldType); 48 | if (value == null) 49 | { 50 | Debug.LogWarning($"Dependency Injection: Can't find component '{field.FieldType.FullName}' in game object '{go.name}' to inject into field '{field.Name}' of component '{componentType.FullName}' of game object '{gameObject.name}'."); 51 | continue; 52 | } 53 | } 54 | 55 | field.SetValue(component, value); 56 | } 57 | } 58 | } 59 | } 60 | 61 | -------------------------------------------------------------------------------- /Scripts/Injector.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: a2e610e89f5dc994aa7d9e978fab61c7 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "com.longbunnylabs.dependencyinjection", 3 | "version": "1.0.0", 4 | "displayName": "Dependency Injection", 5 | "description": "Dependency injection utility for Unity.", 6 | "unity": "2019.4", 7 | "author": { 8 | "name": "Long Bunny Labs", 9 | "email": "minglun.chou@gmail.com", 10 | "url": "https://TheAllenChou.github.com" 11 | }, 12 | "keywords": [ 13 | "Dependency Injection" 14 | ] 15 | } -------------------------------------------------------------------------------- /package.json.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: ddd5ca65448e97a4087cefc8836014e7 3 | TextScriptImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | --------------------------------------------------------------------------------