Last active
April 17, 2021 04:40
-
-
Save hadashiA/ea4e5b0039c39ab84902973f3c6747c0 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
using UnityEngine; | |
using VContainer; | |
using VContainer.Unity; | |
public class AutoInjector : MonoBehaviour | |
{ | |
void Awake() | |
{ | |
var lifetimeScope = LookupScope(); | |
if (lifetimeScope != null) | |
{ | |
lifetimeScope.Container.InjectGameObject(gameObject); | |
} | |
} | |
LifetimeScope LookupScope() | |
{ | |
// Find closest | |
var t = transform.parent; | |
while (t != null) | |
{ | |
var scope = t.GetComponentInChildren<LifetimeScope>(); | |
if (scope != null) | |
return scope; | |
t = t.parent; | |
} | |
// Find root | |
var rootGameObjects = gameObject.scene.GetRootGameObjects(); | |
foreach (var root in rootGameObjects) | |
{ | |
var scope = root.GetComponentInChildren<LifetimeScope>(); | |
if (scope != null) | |
return scope; | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment