简体   繁体   中英

Why can't I change elements in this array

In Unity I create five lists of bools and put them in a jagged array as shown below (in my gamecontrol script). I initialize the 5 List in the inspector in unity, so no initialization is needed in code. During runtime I can access these lists from the inspector.

public class GameControl : MonoBehaviour {
    public static GameControl control;
        public List<bool>[] ascensionUpgrades;
        public List<bool> ascensionUpgrades_0;
        public List<bool> ascensionUpgrades_1;
        public List<bool> ascensionUpgrades_2;
        public List<bool> ascensionUpgrades_3;
        public List<bool> ascensionUpgrades_4;

    void Awake () {

            if (control == null) { 

                DontDestroyOnLoad (gameObject);
                control = this;

            } else if (control != this) {

                Destroy (gameObject);

            }

    ascensionUpgrades = new List<bool>[] {ascensionUpgrades_0, ascensionUpgrades_1, ascensionUpgrades_2, ascensionUpgrades_3, ascensionUpgrades_4};
    }

} At a certain point in the game I do load a new scene, gamecontrol persists due to the dontdestroyonload command. Afterwards when I want to change the values of the bools from another scrupt it looks like this:

GameControl.control.ascensionUpgrades[0][0] = true;
Debug.Log ("Upgrade changed_A?: " + GameControl.control.ascensionUpgrades[0][0]);
Debug.Log ("Upgrade changed_B?: " + GameControl.control.ascensionUpgrades_0[0]);

The value of ascensionUpgrades_0[0] is not set to true. But when I print the value of ascensionUpgrades[0][0] that is indeed true. I expect them to both be true, as I've made the jagged array to better organize and access the bool lists. Debug Log does not show any errors. Can you help me find out where the problem is?

The problem is that ascensionUpgrades is only updated once, on Awake. When you load a new scene, Awake won't be called again on that script, so it will have the same values as before.

Possible solution would be to make a method that updates ascensionUpgrades when you load a new scene. For example

SceneManager.LoadScene(1);
//change other ascensionUpgrades arrays here
GameControl.control.UpdateAscensionUpgrades();

Then in GameControl, you add

public UpdateAscensionUpgrades(){
    ascensionUpgrades = new List<bool>[] {ascensionUpgrades_0, ascensionUpgrades_1, ascensionUpgrades_2, ascensionUpgrades_3, ascensionUpgrades_4};
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM