Hy everyone I have been trying to figure this out, to create a new ball if X is pressed,
this is the farrest I went and I just don't know how to do this, when I run it it loads but when I press X error says:
An unhandled exception of type 'System.NullReferenceException' occurred in First.exe <-----------------------
ball[count].Update();
So here is my code:
Game1.cs
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Sprite backgnd;
Item[] ball;
int count = 0;
int x = 80;
int y = 80;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
graphics.PreferredBackBufferHeight = 600;
graphics.PreferredBackBufferWidth = 750;
}
protected override void Initialize()
{
ball = new Item[5];
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
backgnd = new Background(Content.Load<Texture2D>("map"), new Rectangle(0, 0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height));
if (count <= 4)
{
ball[count] = new Item(Content.Load<Texture2D>("ball"), new Rectangle(x, y, 80, 80), new bool());
}
}
protected override void UnloadContent()
{
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
// ------------------------------------------------------------------------------------------------------------XXXXX
if (Keyboard.GetState().IsKeyDown(Keys.X))
{
ball[count].Check1 = true;
count++;
}
ball[count].Update();
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
backgnd.Draw(spriteBatch);
if (ball[count].Check1 == true)
{
foreach (Item count in ball)
{
count.Draw(spriteBatch);
y += 90;
x += 90;
}
}
spriteBatch.End();
base.Draw(gameTime);
}
}
Sprite class:
namespace First
{
class Sprite
{
public Texture2D texturee;
public Rectangle rectan;
public bool Check1;
public virtual void Update()
{
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(texturee, rectan, Color.White);
}
}
// ---------------------------------------------------------------------Background
class Background : Sprite
{
public Background(Texture2D newTexture, Rectangle newRectangle)
{
texturee = newTexture;
rectan = newRectangle;
}
}
// ----------------------------------------------------------------------Item
class Item : Sprite
{
public Item(Texture2D newTexture, Rectangle newRectangle, bool newCheck)
{
Check1 = newCheck;
texturee = newTexture;
rectan = newRectangle;
}
public override void Update()
{
if (Keyboard.GetState().IsKeyDown(Keys.Right) && Check1 == true)
{
rectan.X += 2;
}
if(Keyboard.GetState().IsKeyDown(Keys.Left) && Check1 == true)
{
rectan.X -= 2;
}
}
}
}
Thanks in advanced!