1

When I try to call this function I get NullreferenceException, if the code looks weird thats because I'm translating from c++ to c#.

public class MyPlayer_t
{
    int pLocal;
    public int Team;
    public int Health;
    public float[] Position = new float[3];

    public void ReadInformation()
    {
        pLocal = Mem.ReadInt(Client + playerBase);
        Team = Mem.ReadInt(pLocal + teamOffset);
        Health = Mem.ReadInt(pLocal + healthOffset);
        for (int i = 0; i < 3; i++)
        {
            Position[i] = Mem.ReadFloat(pLocal + Pos);
        }
    }
}

MyPlayer_t MyPlayer;

// This is how I call it
MyPlayer.ReadInformation();
0

3 Answers 3

2

You have to make object/instance of class using new keyword:

 MyPlayer_t MyPlayer = new MyPlayer_t();
 MyPlayer.ReadInformation();

Here is MSDN Reference to learn about the classes in C#.

Sign up to request clarification or add additional context in comments.

Comments

2

Try and create an instance, and then call it.

var player = new MyPlayer_t();
player.ReadInformation();

If you wanted to actually call it as you've suggested, the class would need to be static, see the following C# static vs instance methods

Comments

1

This is reasonable. You have at first create an instance of the class. Like below:

MyPlayer_t myPlayer = new MyPlayer_t();

Then you can call it's method called ReadInformation like below:

myPlayer.ReadInformation();

The reason why you were getting this error was the fact that this line of code

MyPlayer_t MyPlayer;

creates a variable that can hold an object of type called MyPlayer_t. Since you don't assign to this variable a value, it gets it's default value, which is null. Then you try to call a method called ReadInformation on the the type that is stored in variable called MyPlayer. However, since MyPlayer is null you get this exception.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.