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

Prefab Instantiation call method after start

Discussion in 'Scripting' started by vladstorm_, Jan 9, 2014.

  1. vladstorm_

    vladstorm_

    Joined:
    Nov 26, 2013
    Posts:
    184
    I have a problem.

    I have a class Label which is drawing the text. Label is depending of some resources (image characters and stuff).
    I also have a main object in my scene called Resources. When my game is loading. i'm loading resources.
    Code (csharp):
    1. public class Resources : MonoBehaviour {
    2.     public Dictionary<char, Sprite> chars; //chars for font
    3.  
    4.     void Awake(){
    5.         loadFont("font33chars", chars); //for font 33
    6.     }
    7. }
    Then, i'm using these loaded characters to draw the text.
    Code (csharp):
    1. public class Label : MonoBehaviour {
    2.  
    3.     void Start(){
    4.         chars = singleton.i.resources.chars;
    5.         drawText("ba bla "); //depending on chars
    6.     }
    Lets say I have many labels in my game and this works totally fine.
    Later I wanted to create this Label in runtime using prefab (which is in the resources folder).
    it's also pretty easy
    Code (csharp):
    1.         var pfLabel = (GameObject)Resources.Load("Label", typeof(GameObject));
    2.         var label = (GameObject)Instantiate(pfLabel, transform.position, Quaternion.identity);
    3.         label.GetComponent<whatever>().drawText("bla bla runtime")
    and here there's a problem. because when i'm calling method drawText (which is depending on method start) - i'm realizing that start didnt run yet. so, my characters are not loaded and i cant draw a text.

    i read this article
    http://forum.unity3d.com/threads/24986-prefab-instantiation-start-problem
    but in my case i can't do it like this.
    I can't use Awake method in Label to load resources.
    because i'm using Label on the scene and as a prefab in the same time (maybe its wrong).
    and when it's loading on the scene then when Label.Awake is called - my resources are not ready.

    this is really confusing. i hope you understood. Tell me what to do in this situation.
     
  2. deadfire52

    deadfire52

    Joined:
    Jun 15, 2011
    Posts:
    101
    I think this solves your problem:

    From here: http://docs.unity3d.com/Documentation/ScriptReference/MonoBehaviour.Awake.html
     
  3. vladstorm_

    vladstorm_

    Joined:
    Nov 26, 2013
    Posts:
    184
    yea i know... but i can't use myLabel.Awake. i just wrote. because when i'm using the object in the scene and unity is calling myLabel.Awake myResources(my class with resources) are not loaded yet.
    Im using myRecourses.Awake - to load resources and then myLabel.Start to get those resources..