I am making a game using C# with the XNA framework. The player is a 2D soldier on screen and the user is able to fire bullets. The bullets are stored in an array. I have looked into using Lists and arrays for this and I came to the conclusion that an array is a lot better for me, as there will be a lot of bullets firing and being destroyed at once, something that I read Lists don’t handle so well.
After reading through some posts on the XNA forums, this came to my attention:
http://forums.xna.com/forums/p/16037/84353.aspx
I have created a struct like so:
// Bullets
struct Bullet
{
Vector2 Position;
Vector2 Velocity;
float Rotation;
Rectangle BoundingRect;
bool Active;
}
And I made the array like this:
Bullet[] bulletCollection = new Bullet[100];
But when I try to do some code like this:
// Fire bullet
if (mouseState.LeftButton == ButtonState.Pressed)
{
for (int i = 0; i < bulletCollection.Length; i++)
{
if (!bulletCollection[i].Active)
{
// something
}
}
I get the following error:
‘Zombie_Apocalypse.Game1.Bullet.Active’
is inaccessible due to its protection
level
Can anyone lend a hand? I have no idea why this error is popping up, or even if I’m declaring the array properly or anything… as the post on the XNA forums doesn’t go into detail about that.
Thank you for any help you can provide. 🙂
I believe C# makes members private by default, so you’d simply need to make
Activea public field:More advisable would be to make it a property with a public
getaccessor, keeping thesetprivate:Update (for those arriving at this question just now):
Alternately, it may be a better idea (whether for better performance or to turn fewer heads among your game developer colleagues) to use a
readonlyfield for this purpose:In the latter case you would need to set the value of
Activein your type’s constructor.I originally answered this question from the perspective of a non-game developer, and so this answer (like anything you read here or elsewhere on the internet) should be taken with a grain of salt. I maintain that using a property to hide the setter on a field—whether within a struct or a class—makes sense in typical applications. Comments that others have left lead me to believe that wrapping a field in a property is not the norm for games, however (due to understandable performance considerations); and so you can probably safely ignore my final suggestion.