Why arrays don't set on void Start() ?
So I have problem, my arrays don't set on spot.
public static int currentHealth;
public static int currentXP;
public static int currentLevel;
public static int currentAttack;
public static int currentDefense;
public static int maxHealth;
public static int currentMana;
public static int maxMana;
public static int[] needXPForLevel;
public static int[] defenseOnLevel;
public static int[] hpOnLevel;
public static int[] attackOnLevel;
public static int[] manaOnLevel;
public static bool set;
//Don't destroy:
private static bool created = false;
void Start () {
if (!created) {
GameObject.DontDestroyOnLoad (transform.gameObject);
created = true;
} else {
Destroy (gameObject);
}
}
I have this class with variables and when i'm setting them from another class, they don't set on spot.
void Start () {
Save.needXPForLevel = needXPForLevel;
Save.defenseOnLevel = defenseOnLevel;
Save.hpOnLevel = hpOnLevel;
Save.attackOnLevel = attackOnLevel;
Save.manaOnLevel = manaOnLevel;
}
When i try to use those arrays I get error that they're out of index.
expText.text = "" + Mathf.Floor (((float)Save.currentXP / Save.needXPForLevel [Save.currentLevel + 1]) * 100) + "%";
Well, i tried to fix that, and it fixed it:
if (Save.needXPForLevel.Length == 0) {
Save.needXPForLevel = needXPForLevel;
Save.defenseOnLevel = defenseOnLevel;
Save.hpOnLevel = hpOnLevel;
Save.attackOnLevel = attackOnLevel;
Save.manaOnLevel = manaOnLevel;
}
expText.text = "" + Mathf.Floor (((float)Save.currentXP / Save.needXPForLevel [Save.currentLevel + 1]) * 100) + "%"; //No error this time
So i have question, why my arrays doesn't set on start ?
Have you tried to set the arrays through the Awake function rather then Start? It is like $$anonymous$$onoBehaviours constructor, it is executed before Start methods in scripts.
When is the code that throws the error executed? Is it possible that it's executed before your Start () even ran?
As Landern says, you should probably make your Start () an Awake()
Answer by lollypap54 · Oct 27, 2016 at 11:21 AM
It fixed it when i used void Awake() function.