V
V
Vladislav2015-11-22 15:57:20
C++ / C#
Vladislav, 2015-11-22 15:57:20

How to properly initialize data in Unity C#?

there are 2 classes

public class GameController : MonoBehaviour {
    public MainDeck deck;

    void Start () {
        GameObject deckRespawn = GameObject.Find("deckRespawn");
        deck = Instantiate(deck, deckRespawn.transform.position, deckRespawn.transform.rotation) as MainDeck;
        
         //здесь я надеялся, что метод start() в MainDeck уже выполнился и очередь заполнилась, попробую 
         // вывести длину очереди
         Debug.Log(deck.Cards.Count); //выводит 0
    }
}

and the MainDeck class itself
public class MainDeck : MonoBehaviour {
    public Queue<Card> Cards = new Queue<Card>();
    private GameObject[] prefabs;
    private static int DECK_SIZE = 30;
    void Start () {
        prefabs = Resources.LoadAll<GameObject>("cards");
        populateDeck(DECK_SIZE);
    }

    
    private void populateDeck(int deckSize)
    {
        for (int i = 0; i < deckSize; i++)
        {
            Card card = new Card();
            card.damage = Random.Range(0, 100);
            card.health = Random.Range(200, 1000);
            card.id = i;
            card.image = prefabs[Random.Range(0, prefabs.Length)];
            Cards.Enqueue(card);
        }
    }
}

The very question is why, with Instantiate, the start () method works later than the Instantiate call itself, that is, as I indicated in the comment, it displays a length of 0, but nevertheless I checked that the Queue is full and its length is 30, but later. How should I best initialize the resources in such a case? How is this done in unity?
Of course, I have already read about the awake () method, but is it correct?
It is possible even to throw some example I will be glad.
PS I only downloaded unity yesterday, and I'm getting to know C# on a par with unity, so if this is an obvious question, then ...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Pavlov, 2015-11-22
@Div100

This is exactly the case when your code needs to be written in Awake(), and not in Start(). Awake() is run immediately after the game starts (for each object), then the initial setup of all objects takes place, and after that Start() is launched (again, for each object). Unity does not specify in what order the scene objects will be initialized. Therefore, in Awake() write code related to this very object, and write code related to other objects in Start().

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question