2

I'm working on building an icosphere, and I've gotten as far as the draw portion of the code, but I keep getting a NullReferenceException was unhandled error. I know which bt of code it's pointing at, but I don;t know what's actually wrong or how to fix it.

Here's the class code:

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace Icosahedron_Test
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;

    Camera camera;

    VertexPositionColor[] verts;
    VertexBuffer vertexBuffer;

    BasicEffect effect;

    Matrix worldTranslation = Matrix.Identity;
    Matrix worldRotation = Matrix.Identity;

    int radius = 1; //planet radius
    int refinement = 2;  // number of times to refine surface
    TriXYZ[] vertices; // array containin vertex locations

    Icosahedron planet;

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
    }

    /// <summary>
    /// Allows the game to perform any initialization it needs to before starting to run.
    /// This is where it can query for any required services and load any non-graphic
    /// related content.  Calling base.Initialize will enumerate through any components
    /// and initialize them as well.
    /// </summary>
    protected override void Initialize()
    {
        camera = new Camera(this, new Vector3(0, 0, 5),
            Vector3.Zero, Vector3.Up);
        Components.Add(camera);


        planet = new Icosahedron(radius, refinement, vertices); // create the planet object ( the icosphere )
        vertices = planet.InitializeArray();  // fill the initial verticies list (TriXYZ[])

        //Here is where you will get the world radius and number of time to refine. For now, use constants

        vertices = planet.Refine(vertices, refinement);  // subdivide the triangles as many times as is specified by refinement variable

        // at this point, I should be able to move on to draw and create the list for drawing the triangles of the icosphere

        base.Initialize();
    }

    /// <summary>
    /// LoadContent will be called once per game and is the place to load
    /// all of your content.
    /// </summary>
    protected override void LoadContent()
    {
        // Create a new SpriteBatch, which can be used to draw textures.
        spriteBatch = new SpriteBatch(GraphicsDevice);

        //Initialize Verticies
        VertexPositionColor[] verts;

        verts = planet.BuildList(vertices);

        //set vertex data in vertexBuffer
        vertexBuffer = new VertexBuffer(GraphicsDevice, typeof(VertexPositionColor),
            verts.Length, BufferUsage.None);
        vertexBuffer.SetData(verts);

        //Initialize BAsic effect
        effect = new BasicEffect(GraphicsDevice);
    }

    /// <summary>
    /// UnloadContent will be called once per game and is the place to unload
    /// all content.
    /// </summary>
    protected override void UnloadContent()
    {
        // TODO: Unload any non ContentManager content here
    }

    /// <summary>
    /// Allows the game to run logic such as updating the world,
    /// checking for collisions, gathering input, and playing audio.
    /// </summary>
    /// <param name="gameTime">Provides a snapshot of timing values.</param>
    protected override void Update(GameTime gameTime)
    {
        // Allows the game to exit
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            this.Exit();

        //Translation
        KeyboardState keyboardState = Keyboard.GetState();
        if (keyboardState.IsKeyDown(Keys.Left))
            worldTranslation *= Matrix.CreateTranslation(-.01f, 0, 0);
        if (keyboardState.IsKeyDown(Keys.Right))
            worldTranslation *= Matrix.CreateTranslation(.01f, 0, 0);
        if (keyboardState.IsKeyDown(Keys.Up))
            worldTranslation *= Matrix.CreateTranslation(0, .01f, 0);
        if (keyboardState.IsKeyDown(Keys.Down))
            worldTranslation *= Matrix.CreateTranslation(0, -.01f, 0);
        //Rotation
        worldRotation *= Matrix.CreateFromYawPitchRoll(
            MathHelper.PiOver4 / 60,
            0,
            0);


        base.Update(gameTime);
    }

    /// <summary>
    /// This is called when the game should draw itself.
    /// </summary>
    /// <param name="gameTime">Provides a snapshot of timing values.</param>
    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);
        GraphicsDevice.SetVertexBuffer(vertexBuffer);

        //Set object and camera info
        effect.World = worldRotation * worldTranslation * worldRotation;
        effect.View = camera.view;
        effect.Projection = camera.projection;
        effect.VertexColorEnabled = true;

        //Begin effect and draw for pass
        foreach (EffectPass pass in effect.CurrentTechnique.Passes)
        {
            pass.Apply();

            GraphicsDevice.DrawUserPrimitives<VertexPositionColor>
                (PrimitiveType.TriangleList, verts, 0, (verts.Length/3));
        }

        base.Draw(gameTime);
    }
}
}

The portion of code it's pointing at is this:

GraphicsDevice.DrawUserPrimitives<VertexPositionColor>
    (PrimitiveType.TriangleList, verts, 0, (verts.Length/3));

Does anyone see what's causing this problem?

5
  • 2
    Have you tried any debugging? Set a breakpoint at the line and see if verts or GraphicsDevice is null. Commented Jul 19, 2011 at 16:53
  • Make sure all of verts dependent variables are themselves non-null / have data. Commented Jul 19, 2011 at 16:53
  • Can you not debug and examine the value of the various things in there to see which of them is null or which of them is causing the NRE? Commented Jul 19, 2011 at 16:53
  • I'm very new at this, and do not know exactly how I would go about debugging them. And none of the verts variables are null, I checked that. Commented Jul 19, 2011 at 16:54
  • @Patrick Reynolds - A null object is a reference to nothing. Since you cannot reference nothing you can understand the problem. You first need to determine the reason VertexPositionColor[] is null. I can tell you that the problem is with either your planet or vertices variable. What exactly does BuildList do? You claim that none of your verts variables are null but they are. If they were not null YOU WOULD NOT BE GETTING THIS EXCEPTION. Commented Jul 19, 2011 at 16:55

6 Answers 6

7

verts is null because the variable is never getting assigned. Your LoadContent() method creates a verts inside of its scope, which ignores the one that is a member of your class.

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

2 Comments

Why verts is not assigned? What about line verts = planet.BuildList(vertices); in the LoadContent() method?
I removed that declaration and only used the class-level declaration, that fixed it, thank you. Now to figure out why it's only drawing one triangle.
1

This is a general answer for this kind of issue.

Run your code in the debugger. When it stops due to the unhandled null reference, hover your mouse over each item in the code line it stopped on. It should say, "null" for the one that is null. If your tooltips aren't working, click each item and use QuickWatch (Shift+F9) to display the value.

Comments

0

verts is probably null when trying to access verts.Length ? Check with the debugger by setting the breakpoint there and inspecting yourself.

Comments

0

I can assume that when it accessing verts.Length verts is null. But why you can not add Debug.WriteLine() outputs to see what exactly happens, or simply put a break point or Debugger.Break() call?

Comments

0

I would venture to guess that verts is null, this is based on the initialization.

Comments

0

In addition to all posts here, make sure that you enable exception handling in VS:

enter image description here

Choose "Common language runtime exceptions" check box and most likely VS will lead you on exact line where you got a problem.

EDIT

You can find it in VS menu: Debug-> Exceptions.

Hope this helps.

Regards.

2 Comments

@Tigran - It should be enabled by default.
not very sure on this, honestly... to me it seems that it's not enabled when you've just installed it, cause it happened on the machine of one of mine collegues just, kind of month ago.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.