Reputation: 25
I have a class named Ball (for pong project) and I need to pass the Texture2D through the Main Constructor as so:
Ball.cs
public class Ball
{
Texture2D _ballSprite;
private float _ballSpeed;
private Vector2 _ballMovement;
private Vector2 _ballPosition;
private const int WINDOW_WIDTH = 800;
private const int WINDOW_HEIGHT = 600;
public Ball(Texture2D sprite)
{
_ballSprite = sprite;
}
and then in the Main Game1.cs
Ball ball = new Ball();
What should I pass though the parameters in Main to have the Texture2D appear?
Upvotes: 0
Views: 164
Reputation: 627
You shouldn't pass Texture2D
in constructor. Graphic resources like Texture2D
can become disposed while game is running in event of graphic device being reset. And you will need a new instances of all Texture2D
objects each time that happens.
Therefore in XNA all content loading of graphical resources should be done inside LoadContent()
method. Your Game
class overrides LoadContent()
method. There you can load your texture like this: byBall.BallSprite = Content.Load<Texture2D>("balltexture");
(you need to make BallSprite
property public in that case)
Or you could create a method for loading inside Ball class
public void LoadContent(Content content)
{
_ballSprite = content.Load<Texture2D>("balltexture");
}
and then call myBall.LoadContent(Content)
from overriden Game
class LoadContent()
method.
Note that that Content
object is ContentManager
and will in case you load same texture multiple times, load that texture in memory only once (first time load is called). For all subsequent calls same Texture2D
instance will be returned.
Game.LoadContent()
method is called by XNA before first update and each time graphic device is reset (that can happen for number of reasons at any time). So you need to be careful what you do inside LoadContent()
method. If you would for instance try to create Ball
class instance inside LoadContent()
, that ball instance could be replaced by new ball instance at any time mid game and _ballSpeed
, _ballMovement
, _ballPosition
values would be lost.
Upvotes: 2