0
\$\begingroup\$

I have a project in which I'm trying to remove the "collision box" (Rectangle class) of one of my enemy. My game logic basically is:

foreach (Enemy e in Enemy.enemiesOnScreen) {
            if (e._isDead) {
                e._collisionBox = new Rectangle(0, 0, 0, 0);
            }
            else {
                e.Update(gameTime);
            }     
        }

What I wrote works perfectly, but wouldn't that be subject to memory overflow (for a much higher number of instances) or bad optimization in a real game project ?

\$\endgroup\$
8
  • \$\begingroup\$ Not familiar with xna but have you tried e._collisionBox = null; or something similar? \$\endgroup\$ Nov 2, 2018 at 11:05
  • \$\begingroup\$ Yup I've already tried that. Setting it to null doesn't work, it's not accepted. \$\endgroup\$
    – Muska
    Nov 2, 2018 at 12:19
  • \$\begingroup\$ If null isn't accepted, then it sounds like your Rectangle type is a struct. Assigning a new instance of a struct to an existing field does not cause memory allocation, as discussed previously here \$\endgroup\$
    – DMGregory
    Nov 2, 2018 at 12:32
  • \$\begingroup\$ Is there a reason you need to remove the collision box from a dead enemy? Have you considered doing a check if an enemy is dead in your collision detection code instead of checking vs an empty box? Even if a new struct does not allocate memory it feels somewhat wasteful to construct an object each frame (presumably) just to not use it. \$\endgroup\$
    – Mikael
    Nov 2, 2018 at 13:36
  • \$\begingroup\$ @DMGregory Thanks for the link, I got it now. Assigning a new instance of a struct doesn't allocate memory anywhere else since the struct already allocates storage memory for its values. \$\endgroup\$
    – Muska
    Nov 2, 2018 at 15:05

1 Answer 1

1
\$\begingroup\$

Since the Rectangle class is a struct, all the storage memory allocation is already done. In this case, assigning the 0, 0, 0, 0 values to my rectangle to "remove" it from the scene is FINE and will not cause any memory / optimization issues in a much bigger project with much more instances.

Althought I found a better alternative which is :

e._collisionBox = Rectangle.Empty;

Easier and more readable code. Still don't know if this is the best option in this situation but, I'll be fine with that.

\$\endgroup\$

You must log in to answer this question.

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