-1
\$\begingroup\$

I'm looking to set a leader from an array of sprites, I keep on getting a NullReferenceException was unhandled error from within my main game class when calling the UpdateMouse Method. What have I dont wrong here?

class MouseSprite
{


    Random random = new Random();
    private MouseSprite leader;

    public void UpdateBoundaryBox()
    {
        mouseBounds.X = (int)mousePosition.X - mouseTexture.Width / 2; mouseBounds.Y = (int)mousePosition.Y - mouseTexture.Height / 2;
    }

    public void UpdateMouse(Vector2 position, MouseSprite [] mice, int numberMice, int index)
    {


        Vector2 catPosition = position;
        int enemies = numberMice;
        this.alive = true;

        mice[random.Next(0, mice.Length)] = leader;
\$\endgroup\$
1

2 Answers 2

0
\$\begingroup\$

leader is uninitialized. I assume you're trying to pick a random leader, not set the leader to some mouse randomly (overwriting the mouse stored there with null). You want to swap your assignment statement.

leader = mice[random.Next(0, mice.Length)];
\$\endgroup\$
3
  • \$\begingroup\$ random value is calculated right... it returns a number between 0 and mice.Lenght-1, remmeber that min value is inclusive and max value is exclusive... msdn.microsoft.com/en-us/library/2dx6wyd4.aspx \$\endgroup\$
    – Blau
    Dec 8, 2012 at 16:33
  • \$\begingroup\$ Ah, true enough, I'm used to inclusive randoms. \$\endgroup\$
    – House
    Dec 8, 2012 at 16:34
  • \$\begingroup\$ even swapping them around I still get the same error \$\endgroup\$
    – Craig
    Dec 8, 2012 at 16:46
-1
\$\begingroup\$

Null reference exceptions are thrown because you are trying to access to a reference typed variable that is not assigned.

In the UpdateMouse method code, the only candidate to throw that exception is the array, that maybe is not assigned, check it.

\$\endgroup\$
3
  • \$\begingroup\$ This is a symptom, not a solution. While it may be obvious to you or I how to fix this, this answer should still include a solution. As it stands, it's just a suggestion on what's wrong, instead of how to fix it. So more of a comment. \$\endgroup\$
    – House
    Dec 10, 2012 at 19:12
  • \$\begingroup\$ "Check it" is not a solution... \$\endgroup\$
    – House
    Dec 10, 2012 at 23:45
  • \$\begingroup\$ :P ... the question is "What have I dont wrong here?" Mine is a simple answer that complements yours. If you see the code and where is throwed the exception... is the more reasonable... your answer is more heuristic and other approach to solution... is funny that I could downvote you by an objetive fail in your answer... and you downvote me by subjetive criteria... \$\endgroup\$
    – Blau
    Dec 11, 2012 at 9:27

Not the answer you're looking for? Browse other questions tagged .