I have this List of character objects. I would like to make so that every time I select a character, the game deselect all other character. In this character class I have a variable called selected that is true if selected and false otherwise.
What I want is for only one character to have selected = true while the rest is false. Anyone know how to do this?
There are several ways to go about this.
One of them, and in my opinion the best, is to have the (presumed) ObjectSelector
class - that is responsible for the selection process - manage the selected character.
For instance, you would have a field public Character SelectedCharacter;
on the ObjectSelector
class and assign it with the selected character.
That way you only have one character that can be selected - the one assigned to SelectedCharacter
.
Another way is with old-fashioned iteration:
List
in C# has a built-in method called ForEach
that behaves pretty much like a foreach
loop - it invokes the provided delegate on each of the List elements. So you would do it like:
public void SelectCharacter(Character selectedCharacter)
{
CharacterList.ForEach(character => character.Selected = (character == selectedCharacter));
}
What happens there is that you set the characters’s Selected property to true
if it’s the actually selected character, or to false
otherwise.
The portion (character == selectedCharacter)
is just like having an if
statement as it returns the expression’s evaluation.
Set all items to false. Then set the selected item to true.
foreach(bool value in myList) value = false;
myList[selected] = true;