Skip to content

Optional Injection for MonoBehaviours #801

@ModischFabrications

Description

@ModischFabrications

I have a Unity project that builds to a VR + NonVR solution with a shared codebase, but different objects within the scene. I am able to remove objects during building and have no problem checking everything in code.

My problem: VContainer injection cares deeply that [Inject] works and crashes out if not, but I want to have cases like this were I expect (xr) references to be missing.

My proposal:

        [Inject(Optional = true)]
        public void Construct([CanBeNull] TeleportationProvider teleportProvider)
        {
            _teleportProvider = teleportProvider;
        }

My current workaround:

        [Inject]
        public void Construct(IObjectResolver container)
        {
            _container = container;
        }

        private void Start()
        {
            // resolve manually to check if XR is actually there; can't hardcode XR reference injection
            if (_container.TryResolve(out _teleportProvider))
                return;

            Log.Warning("No teleportation provider found; might want to remove from build");
        }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions