Sign in to follow this  
SonicD007

[XNA] Trying to use GraphicsDevice for a function in another class

Recommended Posts

SonicD007    464
Hi, I'm messing around with XNA Game Studio 4.0 and I was trying to make a simple function that would create a Texture2D 1x1 pixel so that I could use SpriteBatch.Draw to create rectangles of any size/color that I want instead of using resources for every rectangle I would need to draw.

//this line is in Game1.cs
blankTexture = new Texture2D(GraphicsDevice, 1, 1);


Works fine if I use it in the LoadContent of the class derived from Microsoft.Xna.Game but if I try that in a class that isn't derived from Game, I can't use that same statement in a funtion like:

//this function is in a class called Block
Texture2D CreateBlock()
{
Texture2D newRectangle = new Texture2D(GraphicsDevice, 1, 1);
return newRectangle;
}


It says GraphicsDevice is a type but is being used as a variable. I've tried to look through tutorials to see if anyone had done this but I couldn't find anything. Is there anyway to get this to work?

Share this post


Link to post
Share on other sites
Andy474    694
GraphicsDevice is the name of the class, there is no variable found with the name 'GraphicsDevice' which is the error you get.

This is how I create textures exactly the way you do:


public Texture2D CreateTexture(GraphicsDevice device, Color color, float Alpha)
{
Texture2D t = new Texture2D(device, 1, 1, 1, TextureUsage.None, SurfaceFormat.Color);
Color c = new Color(color, Alpha);
t.SetData<Color>(new Color[] {c});

return t;
}





There not far apart, you almost got it.

The reason it works in LoadContent is beacuse the default class with XNa contains a property called GraphicsDevice which exposes the graphics Device for the current game. pass it as a parameter to your new class or make the class a Game Component

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this