Pyroglyph
Pyroglyph

Reputation: 179

SpriteBatch becoming null when passed? / Drawing a sprite in a different class?

Before marking this as a duplicate question, please read it.

Derived from this: How can I draw a sprite in it's own class?

On the aforementioned question, Jonathan helped me to do this and I solved my original problem. But I wanted to know something else and I didn't have enough rep to comment, so I started up a new question.


So I have an XNA game which I want to add hit numbers to (hit numbers are little numbers that appear for a second when something gets damaged) but I'm struggling to with it. My EnemyTest class has an int called Damage. This is passed to the Player class when they collide so the player knows how much to health take off. But then I need to pass it once more to the HitNumbers class to display that number in a DrawString.

My problem is that I have a Draw() method in HitNumbers which takes SpriteBatch spriteBatch (for the DrawString() and int Damage for the number to display. But the Player class sends the Damage value to the main class then the main class passes that and it's SpriteBatch to HitNumbers which throws a NullReferenceException (apparently the Spritebatch is null, but how can it be null when it's drawing all the other sprites?) But I'm a bit confused, I am aware that something incorrect is staring me in the face but I just can't see it. It's like putting your finger really close to your eye and trying to focus on it. Maybe my brain isn't in the right mood, but I'm hoping someone can help me.

Relevant Part of HitNumbers

public void Draw(SpriteBatch spriteBatch, int damage)
{
    // print 'sbnull' to console if received spritebatch is null
    if(spriteBatch == null)
    {
        Console.WriteLine("sbnull");
    }

    spriteBatch.DrawString(RPG.font, EnemyTest.Damage.ToString(), RPG.hn.PlayerPos, Color.Red);  
}

Relevant Part of Player

public void Damage(int damage)
{
    Health -= damage;

    main.showHitNumber(damage);
}

Relevant Part of RPG (main class)

public void showHitNumber(int damage)
{
    hn.Draw(spriteBatch, damage);
}

Upvotes: 0

Views: 81

Answers (1)

Blau
Blau

Reputation: 5762

Because you have two spritebatch, and you are passing the one it's not initialized.

In this code:

public void showHitNumber(int damage)
{
    hn.Draw(spriteBatch, damage);
}

Put the cursor over "spriteBatch" and click with right mouse button, and select "Search all references". This will show wehre you are using that spritebacth instance.

You will have two situations:

  1. That spritebatch instance is never initialized.
  2. Is initialized, but the method that initialize it, is never called.

Upvotes: 1

Related Questions