Answer the question
In order to leave comments, you need to log in
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
}
}
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);
}
}
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question