1

I'm currently working on a game in c#, but a problem has occurred that has had me stuck. The issue is, that I can't figure out how I can get the assigned value of the string 'sprite' printed out. The game I'm working on will have multiple values assigned to the sprite string, which is the reason why I'm not just assigning a value to the string when it's declared.

For the sake of simplicity, I've reduced the scenario into a more simple example.

    class Program
{
    static void Main(string[] args)
    {
        Player p;
        p = new Player();
        Console.Read();
    }
}

class GameObject
{
    public GameObject(string spriteName)
    {
        Console.WriteLine(spriteName);
    }
}

class Player : GameObject
{
    public static string sprite;

    public Player() : base(sprite)
    {
        sprite = "Test";
    }
}

}

  • 2
    Notice that using `new Player` is completely against the Unity mindset and should *never* be done. You don't `new` GameObjects – Camilo Terevinto Dec 15 '18 at 00:51
  • IMHO you should `public static string sprite = "Test"`. The behavior you are looking at is based because of the order the constructor is executed. – Cleptus Dec 15 '18 at 01:01
  • "For the sake of simplicity, I've reduced the scenario into a more simple example" That is exactly the best way to tell a problem. Making it as simple as possible. – Cleptus Dec 15 '18 at 01:24

2 Answers2

1

The problem here is that the base constructor is called before the derived class constructor, so the value of sprite is null at that time.

Probably the simplest way to fix this is to give a default value to your sprite field when it's initialized (and potentially remove it from the instance constructor, unless you always want the static field to get reset to the default value when an instance constructor is called).

Also, note that you could make it a const if it's value is not ever supposed to change.

And a side note - public fields are normally PascalCase in c#:

class Player : GameObject
{
    public static string Sprite = "Test";

    public Player() : base(Sprite)
    {
    }
}
Rufus L
  • 36,127
  • 5
  • 30
  • 43
0

The base constructor gets called before you assign a value to sprite so you are calling base(null)

MrZander
  • 3,031
  • 1
  • 26
  • 50
  • True. He could introduce a `static` constructor as well, for the static field he has there, so: `static Player() { sprite = "Test"; } public Player() : base(sprite) { }` Or (equivalently) he could just initialize the field where it is declared. __Edit:__ Then he could also consider making the field `static readonly` or `const` (in the last case the "initialization" must be at the declaration). – Jeppe Stig Nielsen Dec 15 '18 at 00:55
  • 1
    You pointed out the problem, I would suggest editing the answer and adding a way to workaround it, or put your link as a "related question" comment in the question. – Cleptus Dec 15 '18 at 01:00