- Home /
Variables are assigned but it returns null
I can't figure out what's the error in my code. I call the function Load from the Game Manager, but it returns null even if the variables are assigned in the inspector.
part of Game Manager:
GameObject [] test = DeathLoad.instance.Load()
print(test); //it returns null
Here's my death load script, which is called from the Game Manager.
DeathLoad:
public class DeathLoad : MonoBehaviour{
public static DeathLoad instance;
//Screens are assigned in the inspector
public GameObject [] screens;
void Awake()
{
if(instance == null) instance = this;
}
public GameObject[] Load()
{
return screens;
}
}
I tried to call the method inside the DeathLoad and it works, but I need to call It from the Game Manager.
Your Load method is setup to return an array of GameObjects, but your 'screens' variable is a single GameObject. I would imagine that type mismatch is causing the problem.
No I made I mistake in copying code, that's not my issue :/
Are you certain your DeathLoad instance is actually being assigned before accessing its members?
Answer by Bunny83 · Jun 24, 2019 at 09:42 AM
Assuming that you don't get any runtime error in the code you're providing, the only reason this could happen is that you have two instances of your "DeathLoad" class.
Try this in your Awake method
void Awake()
{
Debug.Log("DeathLoad::Awake", this);
if(instance == null)
instance = this;
else
Debug.Log("Error instance is not null", instance);
}
If you see more than two of these logs there's something wrong in your setup. When you click on the debug log message, Unity will highlight the context object so you can find the instance that you've stored in your singleton variable.
Note that if you do get runtime errors you have to provide your actual code and tell us exactly what error you get and in which line.
Answer by Htss_samy · Jun 24, 2019 at 10:39 AM
first get 'DeathLoad' class from you gameobject (which gameobject have attach this script). then call your Load() function. ex: GameObject ClassObject = Gameobject.Find("---Your gameObject---"); var DeathLoadclass = ClassObject .getcomponet(); DeathLoadclass .Load();
Your answer
Follow this Question
Related Questions
Calling a variable based on a variables name? 1 Answer
Method returning null, when referenced from another script 0 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Are c# methods arguments stored as local variables? 0 Answers