Thread: XNA code error Value cannot be null.

  1. #1
    Registered User
    Join Date
    Dec 2008
    Posts
    20

    XNA code error Value cannot be null.

    if (animations.ContainsKey(currentAnimation))

    But it stopped working when I had tried to draw a list

  2. #2
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    You're going to have to give a little more context. It looks like animations is a dictionary, but that's not really enough information to know what you need.
    If you understand what you're doing, you're not learning anything.

  3. #3
    Registered User
    Join Date
    Dec 2008
    Posts
    20

    object class here

    Quote Originally Posted by itsme86 View Post
    You're going to have to give a little more context. It looks like animations is a dictionary, but that's not really enough information to know what you need.
    Code:
     class GameObj
        {
            #region Declarations
            public Vector2 worldLocation;
            protected Vector2 velocity;
            protected bool flipped = false;
            protected float drawDepth = 0.85f;
            protected int FrameWidth;
            protected int FrameHeight;
            protected Dictionary<string, AnimationStrip> animations =
            new Dictionary<string, AnimationStrip>();
            protected string currentAnimation;
            protected Rectangle CollisionRectangle;
            private int Minlocxobj;
            private int Minlocyobj;
            private int Maxlocxobj;
            private int Maxlocyobj;
            
            public float health;
    
            #endregion
            public float timer;
         
            public int minlocxobj {
    
                get { return Minlocxobj; }
                set { Minlocxobj = value; }
            }
    
    
            public int minlocyobj
            {
    
                get { return Minlocyobj; }
                set { Minlocyobj = value; }
            }
            
            public int maxlocxobj
            {
    
                get { return Maxlocxobj; }
                set { Maxlocxobj = value; }
            }
    
            public int maxlocyobj
            {
    
                get { return Maxlocyobj; }
                set { Maxlocyobj = value; }
            }
            
            
            public Vector2 WorldLocation
            {
                get { return worldLocation; }
                set { worldLocation = value; }
            }
    
            public int frameWidth
            {
                get { return FrameWidth; }
                set { FrameWidth = value; }
            }
    
            public int frameHeight
            {
                get { return FrameHeight; }
                set { FrameHeight = value; }
            }
    
            public Rectangle objRectangle
            {
                get
                {
                    return new Rectangle(
                      (int)worldLocation.X,
                      (int)worldLocation.Y,
                      FrameWidth,
                      FrameHeight);
                }
            }
            public Rectangle collisionRectangle
            {
                get
                {
                    return new Rectangle(
                        (int)worldLocation.X + CollisionRectangle.X,
                        (int)objRectangle.Y + CollisionRectangle.Y,
                        CollisionRectangle.Width,
                        CollisionRectangle.Height);
                }
                set { CollisionRectangle = value; }
            }
    
     
    
            private void updateAnimation(GameTime gametime)
            {
               
                  timer = (float)gametime.ElapsedGameTime.TotalSeconds;
                if (animations.ContainsKey(currentAnimation))
                {
                    if (animations[currentAnimation].FinishedPlaying)
                    {
                        PlayAnimation(animations[currentAnimation].NextAnimation);
                    }
                    else
                    {
                        animations[currentAnimation].Update(gametime);
                    }
                }
           
            
            
            }
    
            public void PlayAnimation(string name)
            {
                if (!(name == null) && animations.ContainsKey(name))
                {
                    currentAnimation = name;
                    animations[name].Play();
                }
            }
    
    
            public virtual void Update(GameTime gameTime)
            {
    
                float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
    
                
                updateAnimation(gameTime);
                Vector2 moveamount = velocity * elapsed;
                Vector2 newposition = WorldLocation + moveamount;
    
    
    
                /* newposition = new Vector2(
                    MathHelper.Clamp(newposition.X, 0,
                      Camera.WorldRectangle.Width - frameWidth),
                    MathHelper.Clamp(newposition.Y,2 * 5,
                      Camera.WorldRectangle.Height - frameHeight));*/
                WorldLocation = newposition;
    
    
            }
            public virtual void Draw(SpriteBatch spriteBatch)
            {
                if (animations.ContainsKey(currentAnimation))
                {
                    SpriteEffects effect = SpriteEffects.None;
    
                    if (flipped)
                    {
                        effect = SpriteEffects.FlipHorizontally;
                    }
                    spriteBatch.Draw(
                        animations[currentAnimation].Texture,
                       Camera.WorldToScreen(objRectangle),
                        animations[currentAnimation].FrameRectangle,
                        Color.DeepSkyBlue, 0.0f, Vector2.Zero, effect, drawDepth);
    
    
                }
            }
    
    
        }
    }

  4. #4
    Registered User
    Join Date
    Dec 2008
    Posts
    20
    Which flows into my shrimp class

    Code:
     class Shrimp : GameObj
        {
            public float damage = 0.0f;
            private float moveScale = 110.5f;
            public Vector2 targetplayer;
           
            
            public Shrimp(ContentManager content)
            {
                animations.Add("walk",
                    new AnimationStrip(
                        content.Load<Texture2D>(@"shrimp\shrimpwalk"),
                        110,
                        "walk"));
                animations["walk"].LoopAnimation = true;
    
                animations.Add("death",
                    new AnimationStrip(
                        content.Load<Texture2D>(@"shrimp\shrimp_death"),
                        110,
                        "death"));
                animations["death"].LoopAnimation = false;
    
                animations.Add("attack2",
                    new AnimationStrip(
                        content.Load<Texture2D>(@"shrimp\shrimp_attack2"),
                        90,
                        "attack2"));
                animations["attack2"].LoopAnimation = true;
                animations["attack2"].FrameLength = .1005f;
            }
    
            public override void Update(GameTime gameTime)
          
          
            
            
            {
    
                Console.WriteLine("Fish", worldLocation);
                
                collisionRectangle = new Rectangle (100,150,150,150);
    
                
                health = 10;
                frameHeight = 50;
                frameWidth = 50;
    
    
    
    
    
                string newAnimation = "walk";
    
                damage = 20;
                velocity = new Vector2(0, 0);
    
                if (newAnimation == "attack2")
                {
    
                    damage = -20;
    
                }
                if (Vector2.Distance(targetplayer, worldLocation) <= 100)
                {
    
                    newAnimation = "walk";
    
                    if (Vector2.Distance(targetplayer, worldLocation) <= 50)
                    {
                        Console.WriteLine(timer);
                        newAnimation = "attack2";
                       //worldLocation.X = targetplayer.X + 50 ;
                    }
                    if (worldLocation.X < targetplayer.X)
                    {
    
                        velocity = new Vector2(moveScale, velocity.Y);
                        flipped = false;
                        if (worldLocation.Y < targetplayer.Y)
                        {
                            velocity = new Vector2(velocity.X,moveScale);
                        
                        }
                    }
    
                    if (worldLocation.X > targetplayer.X)
                    {
    
                        velocity = new Vector2(-moveScale, velocity.Y);
                        flipped = true;
                        if (worldLocation.Y > targetplayer.Y)
                        {
                            velocity = new Vector2(velocity.X, -moveScale);
    
                        }
                    }
                
                }
    
                
                
                
                
                
                if (newAnimation != currentAnimation)
                {
                    PlayAnimation(newAnimation);
                }
    
                base.Update(gameTime);
            }
    
        }
    }

  5. #5
    Registered User
    Join Date
    Dec 2008
    Posts
    20
    I then have it go into my levelmanger class as a list but its not drawing it

    Code:
    class LevelManager
        {
            private static ContentManager Content;
            private static OcTwo octwo;
            private static List<Shrimp> shrimps = new List<Shrimp>();
            private static Plant plant;
            
            private static lvl1 lvlone;
            public static void Initialize(
    
                ContentManager content,
                OcTwo gameoctwo, lvl1 lvl1game)
            {
                Content = content;
                octwo = gameoctwo;
                lvlone = lvl1game;
    
            }
            public static void loadme() {
                foreach (Shrimp shrimp in shrimps)
                {
                    shrimp.targetplayer = octwo.worldLocation;
                    shrimp.worldLocation = new Vector2(1000, 300);
                }
            
            }
            public static void Update(GameTime gameTime)
            {
                for (int x = 0; x <= 4; x++)
                {
    
                    shrimps.Add(new Shrimp(Content));
                }
    
    
            }
    
    
    
    
              public static void Draw(SpriteBatch spriteBatch)
            {
                foreach (Shrimp shrimp in shrimps)
                    shrimp.Draw(spriteBatch);
              
              }
            }
    
        }

  6. #6
    Registered User
    Join Date
    Dec 2008
    Posts
    20
    And what it loads into for good measure
    Code:
     public class Game1 : Microsoft.Xna.Framework.Game
        {
            GraphicsDeviceManager graphics;
            SpriteBatch spriteBatch;
            OcTwo octwo;
            lvl1 lvlone;
            SoundEffect soundEffect;
            Texture2D titleScreen;
            enum GameState { Starting, Playing };
            GameState gameState = GameState.Starting;
            
            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()
            {
                // TODO: Add your initialization logic here
                this.graphics.PreferredBackBufferWidth = 800;
                this.graphics.PreferredBackBufferHeight = 600;
                this.graphics.ApplyChanges();
                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);
                Camera.WorldRectangle = new Rectangle(100, 200, 160 * 48, 12 * 48);
                Camera.Position = Vector2.Zero;
                Camera.ViewPortWidth = 800;
                Camera.ViewPortHeight = 600;
                titleScreen = Content.Load<Texture2D>(@"Textures\Uwk");
    
                soundEffect = Content.Load<SoundEffect>(@"Sounds\intro");
                
                octwo = new OcTwo(Content);
                lvlone = new lvl1(Content);
                LevelManager.Initialize(Content, octwo,  lvlone);
                // TODO: use this.Content to load your game content here
            }
            private void StartNewGame()
            {
                LevelManager.loadme();
                octwo.worldLocation = new Vector2(338, 492);
            }
            
            /// <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();
    
                KeyboardState keyState = Keyboard.GetState();
                if (gameState == GameState.Starting)
                {
                    soundEffect.Play();
    
                    if (keyState.IsKeyDown(Keys.Space))
                    {
                        StartNewGame();
                        gameState = GameState.Playing;
                        LevelManager.Update(gameTime);
                    }
                }
                if (gameState == GameState.Playing)
                {
                    octwo.Update(gameTime);
                    lvlone.Update(gameTime);
                    LevelManager.Update(gameTime);
    
                    soundEffect.Dispose();
                    // TODO: Add your update logic here
    
                 
                }
                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);
    
                // TODO: Add your drawing code here
                spriteBatch.Begin();
                GraphicsDevice.Clear(Color.Aquamarine);
                if (gameState == GameState.Starting)
                {
    
    
                    spriteBatch.Draw(titleScreen, Vector2.Zero, Color.Wheat);
                }
                if (gameState == GameState.Playing)
                {
                    lvlone.Draw(spriteBatch);
                    LevelManager.Draw(spriteBatch);
                    octwo.Draw(spriteBatch);
                    
    
    
                }
    
    
                spriteBatch.End();
                base.Draw(gameTime);
            }
        }
    }

  7. #7
    Registered User
    Join Date
    May 2003
    Posts
    1,619
    Quote Originally Posted by Demipimp View Post
    if (animations.ContainsKey(currentAnimation))

    But it stopped working when I had tried to draw a list
    Well, just look at the error message:

    "Value cannot be null".

    In that line, there are only two variables, animations and currentAnimation. One of those two is null when this code is executing - in this case, currentAnimation is null because the text indicates an ArgumentNull exception not a NPE.

    So check if currentAnimation exists before trying to use it.
    You ever try a pink golf ball, Wally? Why, the wind shear on a pink ball alone can take the head clean off a 90 pound midget at 300 yards.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 12-02-2011, 06:17 PM
  2. why i dong get accsesing null memory error stuff..
    By transgalactic2 in forum C Programming
    Replies: 27
    Last Post: 03-24-2009, 02:12 PM
  3. error C2065: 'NULL'
    By jamez05 in forum C Programming
    Replies: 4
    Last Post: 07-23-2006, 12:00 PM
  4. accept(ListenSocket, NULL, NULL); cause program to hang?
    By draggy in forum Networking/Device Communication
    Replies: 11
    Last Post: 06-16-2006, 03:40 PM
  5. ASCII code for a NULL character
    By GaPe in forum C Programming
    Replies: 1
    Last Post: 12-09-2001, 05:40 AM