1
\$\begingroup\$

I have loaded a sound effect file into the main class in xna, but when I try to run it in another class I am given this error

{"Object reference not set to an instance of an object."}

I am new to XNA classes so I do not really understand them. Any help as soon as possible is greatly appreciated.

this is part of the main class

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 BreakingOut
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;

    Ball ball;
    Paddle paddle;
    Rectangle screenRectangle;
    bool is1P = true;

    int lives = 3;

    Texture2D startButtonTexture;
    Vector2 buttonVec;

    Texture2D exitButtonTexture;
    Vector2 button2Vec;

    int bricksWide = 10;
    int bricksHigh = 7;
    Texture2D brickImage;
    Brick[,] bricks;

    //rec for menu
    Texture2D menuTexture;
    Rectangle menuRec = new Rectangle(0, 0, 960, 640);
    //rec for pause
    Texture2D pauseTexture;
    Rectangle pauseRec = new Rectangle(0, 0, 960, 640);
    //lose
    Texture2D loseTexture;
    Rectangle loseRec = new Rectangle(0, 0, 960, 640);

    Texture2D winTexture;
    Rectangle winRec = new Rectangle(0, 0, 960, 640);

    //sound effects
    public  SoundEffect BallHitSE;
    SoundEffect WallHitSE;
    SoundEffect StartSE;
    //BGM
    Song menuMusic;
    Song gameMusic;

    bool isGameMusicPlaying = false;
    bool isMenuMusicPlaying = false;

    float pauseTimer;
    float exitTimer;
    float muteTimer;
    float SEmuteTimer;

    //public int brickCount = 70;

    SpriteFont font;

    Vector2 mousePos;

    enum gameStates
    {
        MENU,
        GAME1P,
        LOSE,
        PAUSE,
        WIN,
    }

    gameStates currentState = gameStates.MENU;
    gameStates prevState = gameStates.MENU;

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

        IsMouseVisible = true;

        graphics.PreferredBackBufferWidth = 960;
        graphics.PreferredBackBufferHeight = 640;

        screenRectangle = new Rectangle(
            0,
            0,
            graphics.PreferredBackBufferWidth,
            graphics.PreferredBackBufferHeight);
    }

    /// <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

        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);

        Texture2D tempTexture = Content.Load<Texture2D>("paddle");
        paddle = new Paddle(tempTexture, screenRectangle);

        BallHitSE = Content.Load<SoundEffect>("BallHit");
        WallHitSE = Content.Load<SoundEffect>("WallHit2");
        StartSE = Content.Load<SoundEffect>("Start");
        gameMusic = Content.Load<Song>("gameMusic");
        menuMusic = Content.Load<Song>("menuMusic");

This is the Ball class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace BreakingOut
{
class Ball
{
    Vector2 motion;
    Vector2 position;
    Rectangle bounds;
    bool collided;

    public int brickCount = 70;

    const float ballStartSpeed = 6.4f;
    public float ballSpeed;

    Texture2D texture;
    Rectangle screenBounds;


    SoundEffect BallHitSE;
    //BallHitSE = new SoundEffect

    public Rectangle Bounds
    {
        get 
        {
            bounds.X = (int)position.X;
            bounds.Y = (int)position.Y;
            return bounds;
        }
    }

    public Ball(Texture2D texture, Rectangle screenBounds)
    {
        bounds = new Rectangle(0, 0, texture.Width, texture.Height);
        this.texture = texture;
        this.screenBounds = screenBounds;
        //Different things we tried
        //BallHitSE = Content.Load<SoundEffect>("BallHit");
        //BallHitSE =  new soundeffect(what goes in here?);
        //BallHitSE = Content.Manager.Load("path")

    }

    public void Update()
    {
        collided = false;
        position += motion * ballSpeed;
        ballSpeed += 0.001f;

        CheckWallCollision();
    }

    public void CheckWallCollision()
    {
        if (position.X < 0)
        {
            position.X = 0;
            motion.X *= -1;
            //if (BallHitSE != null)
            //{
                BallHitSE.Play();
            //}
        }
        if (position.X + texture.Width > screenBounds.Width)
        {
            position.X = screenBounds.Width - texture.Width;
            motion.X *= -1;
            //if (BallHitSE != null)
            //{
                BallHitSE.Play();
            //}
        }
        if (position.Y < 0)
        {
            position.Y = 0;
            motion.Y *= -1;
            //if (BallHitSE != null)
            //{
                BallHitSE.Play();
            //}
        }
    }

    public void SetInStartPosition(Rectangle paddleLocation)
    {
        Random rand = new Random();

        motion = new Vector2(rand.Next(2, 6), -rand.Next(2, 6));
        motion.Normalize();

        ballSpeed = ballStartSpeed;

        position.Y = paddleLocation.Y - texture.Height;
        position.X = paddleLocation.X + (paddleLocation.Width - texture.Width) / 2;
    }

    public bool OffBottom()
    {
        if (position.Y > screenBounds.Height)
            return true;
        return false;
    }

    public void PaddleCollision(Rectangle paddleLocation)
    {
        Rectangle ballLocation = new Rectangle(
            (int)position.X,
            (int)position.Y,
            texture.Width,
            texture.Height);

        if (paddleLocation.Intersects(ballLocation))
        {
            position.Y = paddleLocation.Y - texture.Height;
            motion.Y *= -1;
        }
    }

    public void Deflection(Brick brick)
    {
        if (!collided)
        {
            motion.Y *= -1;
            collided = true;
            brickCount -= 1;
        }
    }

    public void Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(texture, position, Color.White);
        for (int i = 1; i < 10; i++)
        {
            var drawPosition = position - (i * motion * 3);
            var colour = Color.Lerp(Color.White, Color.Transparent, i * (20 / 100f));
            spriteBatch.Draw(texture, drawPosition, colour);
        }
    }
}
}
\$\endgroup\$
1
  • \$\begingroup\$ Can you please indicate which line is throwing the exception? Is there any relevant info you can give us from the debugger? Also try and reduce the amount of code you've posted down to only what is relevant, so it's easier to digest for people who haven't seen it before. \$\endgroup\$ Commented Nov 22, 2013 at 7:07

1 Answer 1

0
\$\begingroup\$

Make sure, Ball is instantiated before LoadContent().

Then swap this line

BallHitSE = Content.Load<SoundEffect>("BallHit");

with this

Ball.BallHitSE = Content.Load<SoundEffect>("BallHit");

and change the variable in your Ball class to this

public SoundEffect BallHitSE;
\$\endgroup\$
4
  • \$\begingroup\$ Tried what you said, I get this error Error 1 An object reference is required for the non-static field, method, or property 'BreakingOut.Ball.BallHitSE' \$\endgroup\$
    – Evan
    Commented Nov 22, 2013 at 13:56
  • \$\begingroup\$ This is because you did not instantiate the Ball object. Try changing the variable to "public static SoundEffect BallHitSE;" \$\endgroup\$ Commented Nov 22, 2013 at 15:43
  • \$\begingroup\$ Thank you very much and sorry for the late reply. I was finishing school and am now on holidays. Can you please explain why exactly this works? \$\endgroup\$
    – Evan
    Commented Dec 13, 2013 at 6:47
  • \$\begingroup\$ To be able to access the Field BallHitSE in your Ball class, it needs to be public. The static modifier defines, that the Field belongs to the class itself, and not to the object. So with these changes BallHitSE is accessible, with no need of a Ball instance (which you would create by ball = new Ball()). \$\endgroup\$ Commented Dec 13, 2013 at 7:25

You must log in to answer this question.

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