Sign in to follow this  
TaeKwonDo

c# array question

Recommended Posts

ok, so im making a simple array using a Enemey class I created. The enemey class as you can see has simple stats (hp, mp etc.) I get an error though when I try to modify one of the array elements stats such as:
class Enemey
{
        public int hp;
        public int mp;
        public int str;
        public int def;
        public int mag;
        public int spr;
        public int luk;

        Enemey()
        {
            hp = 0;
            mp = 0;
            str = 0;
            def = 0;
            mag = 0;
            spr = 0;
            luk = 0;
        }
}

class Program
    {
        static void Main(string[] args)
        {
            Enemey[] myEnemies = new Enemey[10];
            myEnemies[0].hp = 5;//this causes an error
            
        }
    }

when I run this program I get an error at runtime talking about a System.NULLReferenceException does anyone know how to fix this or point me in the right way of fixing it? thanks.

Share this post


Link to post
Share on other sites
Tip #1: Read the error message!

NULLReferenceException means you tried to access a NULL reference, i.e. object that is not initialized.

In C#, all non-value types (including classes) must first be initialized with new, just as you intialized your array object. BUT, you only initialized your array, not the elements of your array! Hence when you try to access them, you get the exception.

When you initialize an array, you must manually initialize each of its elements, like this:


Enemey[] myEnemies = new Enemey[10];

for(int i = 0; i <10; i++)
myEnemies[i] = new Enemy();





Good luck! The reference system confused the hell out of me when I first started learning C# too :)

Share this post


Link to post
Share on other sites
Since Enemey is a class you have the 'new' every element in the array


static void Main(string[] args)
{
const int size = 10;
Enemey[] myEnemies = new Enemey[size];
for( int i = 0; i < size; i++ )
{
myEnemies[i] = new Enemey();
myEnemies[i].hp = 5;//this causes an error
}
}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this