Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Resolving incomplete object problem when using IOC.

Discussion in 'Scripting' started by koirat, May 19, 2022.

  1. koirat


    Jul 7, 2012
    So I was basically wondering how do you resolve Dependency injection with IOC when the objects injected in are in incomplete state.

    What I mean by this, imagine you have 3rd party component that is fully Initialized at Start()
    Now some other object is created by IOC and is injected with this incomplete object since it's start was not called yet.
    Is there an official way to resolve such a situation.
  2. Kurt-Dekker


    Mar 16, 2013
    It may be helpful when thinking about these problems to consider that your program is NOT the application.

    Unity is the application. Unity starts and does all of the usual initial program loading steps that any app must do.

    Only once Unity is fully initialized and running does it possibly even have a chance (under certain specific rules) to execute some of your code.

    Only after this point can you do ANYTHING with Unity. This means all your constructor time and static field initializers may never access anything in Unity.

    But in all cases, your code is NOT the application. This may help you think about the problem more constructively.
  3. SisusCo


    Jan 29, 2019
    One possibility is using a preload scene.
    1. Create a preload scene, containing all your problematic 3rd party components.
    2. Add a component to the preload scene with latest possible execution order, which loads the main scene additively during the Start event.
    3. Add a component to the main scene with earliest possible execution order, which starts the game loading process in which the other objects are created.
    Another option would be to use the Decorator pattern: wrap the problematic third party object within another object, and introduce an additional property like
    bool IsReady
    , which clients can use to delay/avoid execution of some code until the object has finished setting up.
    Nit_Ram and Kurt-Dekker like this.