Quantcast
Channel: Questions in topic: "exception"
Viewing all articles
Browse latest Browse all 470

C# NullRefException accessing static class, array value

$
0
0
Hey Guys, This is driving me insane. I decided on using a class array to access upgrade stats instead of a list. But something so seemingly simple is throwing an error and for the life of me I can't see it. Very simply I created a class to hold an array of another class: public static class GlobalVariables { public class statClass { public int Dmg { get; set; } public int FX { get; set; } public int Blast { get; set; } } public class statHolder { public statClass[] chicken = new statClass[3]; public statClass[] sheep = new statClass[3]; public statClass[] pig = new statClass[3]; public statClass[] cow = new statClass[3]; public int[] someInts = new int[5]; } public static statHolder currentStats = new statHolder(); As you can see, I've created an instance of the 'statHolder' class called 'currentStats'. The 'statHolder' class contains 4 arrays of the class 'statClass', which will contain some public values (that are currently uninitialized, which is irrelevant). Now when I try to call or access these values from another class's Start() method:
GlobalVariables.currentStats.chicken[0].Dmg = 5;
I get the good old "NullReferenceException: Object reference not set to an instance of an object". But that is a bold-faced LIE. "chicken[0]" **IS** an instance of statClass as specified by "chicken = new statClass[3];". I'm so angry I want to punch a baby in the face. There's obviously a disconnect between declaring the statClass arrays and accessing them, but I am too close to the forest to see the trees. To check my sanity i created another array with the exact same type of declaration called 'someInts'. Accessing them in exactly the same way works fine:
GlobalVariables.currentStats.someInts[0] = 5;
Can anyone point out to me where my mistake is? Because right now I'm inclined to assume that C# is just being a finicky bitch. Serves me right for trying to do something the easy way I guess. **//// UPDATE ////** Thanks guys, very clear where the disconnect was now. Initial value of a reference **is always null**. public class statHolder { public statClass[] chicken = new statClass[3]{new statClass(), new statClass(), new statClass()}; public statClass[] sheep = new statClass[3]{new statClass(), new statClass(), new statClass()}; public statClass[] pig = new statClass[3]{new statClass(), new statClass(), new statClass()}; public statClass[] cow = new statClass[3]{new statClass(), new statClass(), new statClass()}; }

Viewing all articles
Browse latest Browse all 470


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>