Skip to content

Instantly share code, notes, and snippets.

@hadashiA
Last active April 17, 2021 04:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hadashiA/ea4e5b0039c39ab84902973f3c6747c0 to your computer and use it in GitHub Desktop.
Save hadashiA/ea4e5b0039c39ab84902973f3c6747c0 to your computer and use it in GitHub Desktop.
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