Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Instantation and use of gameobject in same frame

Discussion in 'Scripting' started by hexdump, Nov 24, 2014.

  1. hexdump

    hexdump

    Joined:
    Dec 29, 2008
    Posts:
    443
    Hi,

    I would like to know how you deal with a scenario like this:

    1. When a mouse button is clicked a prefab is instantiated.
    2. This prefab have some components that need initialization and the initialization code is placed in awake and start.
    3. Right after creation (same frame) the gameobjects are passed to a function that will do some calculatiosn with it.
    You see the problem. The initialization hasn't been ran for the different components in the game object. So, 3 won't work or will render a wrong result.

    Solutions I have found (thought about):

    1. After creation wait for next frame with a coroutine (WaitForEndOfFrame) and then, execute step 3(pass this objects now that awake and start has been called to the worker function).
    2. Instantiate the game object and them add it to a list. After all frame work is done when LateUpdate() callback of the behaviour that created the gameobject is called, test if there are newly created gameobjects and pass all these newly created objects to the worker function.
    3. Move initialization code to different inits in each behavour and initialize then manually (really bad aproach).
    Would you mind commenting any other way to accomplish this?
     
  2. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    I was under the impression that Awake ran immediately after something was instantiated. Have you found that not to be the case?
     
  3. Tomnnn

    Tomnnn

    Joined:
    May 23, 2013
    Posts:
    4,148
    I thought so to.

    @hexdump if you change Awake to a public Init, then you can do something like...
    Code (CSharp):
    1. GameObject c = GameObject.Instantiate(prefab);
    2. c.getComponent<script>().init();
    just to be sure it ran. :D
     
  4. hexdump

    hexdump

    Joined:
    Dec 29, 2008
    Posts:
    443
    Yes, it does. Another pal on unity answers suggested it. Sorry for the delay updating the response and thanks for your responses.

    Cheers.