VisualGhost
VisualGhost

Reputation: 49

Reference to multiple objects/variables with 1 name

In C#, I'm making a platform game. The terrains are pictureboxes, and with the collision systems eg. I need to have 1 name to reference to a number of selected pictureboxes, because it would be too much code to make the same function with another picturebox. So, an example, if "picturebox1" and "picturebox2" is referenced as "pictureall", then, if this code is executed:

pictureall.Visible = false;

both "picturebox1" and "picturebox2" would be invisible. So, how can I reference to (in the example) the 2 pictureboxes with 1 name?

Edit: I'm mostly going to use it in If statements. So, like, as example: if (pictureall.Visible == true) MessageBox.Show("true"); If then any picturebox is visible, it would be true.

/Viktor

Upvotes: 0

Views: 124

Answers (2)

Andre Loker
Andre Loker

Reputation: 8408

If you don't want to use a custom collection class as kishore V M suggests, you could put the selection of picture boxes in a collection such as a List<T> and use the available (extension) methods, e.g.

List<PictureBox> pictureBoxes = new List<PictureBox>();

// fill the list
pictureBoxes.Add(...);

// do something to all boxes in the list
pictureBoxes.ForEach(box => box.Visible = true);

// ask something about the boxes in the list
if (pictureBoxes.Any(box => box.Visible))
{
    // at least one box visible
}
// or:
if (pictureBoxes.All(box => box.Visible))
{
    // all boxes visible
}

References:

Upvotes: 0

kishore V M
kishore V M

Reputation: 811

you create a custom class named Grouppictures

  1. This will contain List of pictures as member variable
  2. A Method SetVisibility(bool visible)
  3. In the above method you will loop and set the visibility of all pictures
  4. but you will call the method as GrouppicturesObj.SetVisibity(false);

Upvotes: 1

Related Questions