Cannot access a array in another script
I have 2 scripts and iam trying to acces the array thats made in script 1 but it gives me a nullreferenceexception when i press the start button (which calls Startgame()). Strangely when i use the debug.log in the first script it gives me the corrrect value 100 when i start the game. Game.current.Progress also doesnt have this problem it just works as i expected it to but this is not a array. Is this a bug? Kinda confused now. Do i have to reference a array in a different way than a normal variable?
Script 1:
using UnityEngine;
using System.Collections;
[System.Serializable]
public class Game {
public static Game current = new Game ();
public int Progress;
public float[] Scores;
public Game () {
Progress = new int();
Scores = new float[2];
Scores[0] = 100;
Debug.Log (Scores [0]);
}
}
Script 2 :
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class Menucontroller : MonoBehaviour {
void Start (){
SaveLoad.Load ();
foreach (Game g in SaveLoad.savedGames) {
Game.current = g;
}
if (Game.current.Progress == 0) {
Game.current.Progress = 1;
}
}
public void StartGame () {
Application.LoadLevel (2);
Debug.Log ((Game.current.Scores)[0]);
}
Etcetcetc
shouldnt Debug.Log ((Game.current.Scores)[0]);
be
Debug.Log (Game.current.Scores[0]);
Answer by Barsonax · Oct 10, 2015 at 10:57 PM
I solved it by making a public static variable that i use as a "interface" between my objects. Since i know there will be only 1 instance of this this seemed a quite simple solution to me:
public static ItemDatabase Interface;
Awake() { Interface = this; }
Then i could do somescript.Interface to gain a reference to a script.
I will look in your suggestion though as i have also read there are disadvantages about static variables.
Answer by landon912 · Sep 30, 2015 at 12:06 AM
You need to actually gain a reference to the class instance. You can't simply use a static class qualifier. You can "get" a reference through the other class like this if there is only one instance in the scene:
Debug.Log(FindObjectOfType<Game>().Scores[0]);
However, it'd be better to cache the reference, and use a field.
Even better, you should use the singleton design pattern.
Tried this but since the first script doesnt use monobehavoir this doesnt work. Wouldnt really make sense to me either since i can reference the int in the other script just not the array.
Your answer
Follow this Question
Related Questions
Why i can't read a Variable's Length(Array) 2 Answers
Adding a new GameObject to an Array without overriding the others 0 Answers
help ordering array for planetary gravity 1 Answer
Why are my arrays in arrays null (converting from JSON)? 1 Answer
Object Reference not set somewhere in the List, but can't figure it out. 0 Answers