- Home /
Hold a link to a object in a list.,Reference a List item
I want to have a reference to an object in a list that won't break if I add or remove other objects to the list.
I have ScriptableObject
's saved in a List
. These ScriptableObject
s are cards.
Cards are moved from List deck to List player1; When the card is moved, a canvas image(gameobject) is added to the screen, that pulls the image from the card, however, there is no hard linking to that gameObject
.
What I want to do is remove the correct card from the list when it is played.
For the first card, I can use player1.RemoveAt(i);
but this will misalign all the other cards.
I know there MUST be a way, but I can't find anything.
Thanks for any help
Can't you set the i
th element to null?
private Card PickCard(int index)
{
Card card = list[i];
list[i] = null;
return card;
}
private void PutCardBack(Card card, int index)
{
if(list[i] != null)
throw new System.InvalidOperationException("There is already a card in slot #" + i);
list[i] = card;
}
Answer by andrew-lukasik · Apr 29, 2021 at 01:01 PM
There is a way. Use a ❤ hash map ❤ - collection where an int
,string
etc can constitute a "reference" (similar to int
index for a list) and order doesn't matter.
Let's say you map your cards like this:
Dictionary<int,MyScriptableObject> _map = new Dictionary<int,MyScriptableObject>();
So now when you add a card - create an unique key for it as well:
int key = System.Guid.NewGuid().GetHashCode();// not 100% unique, but good enough
_map.Add( key , card );
Store this key somewhere so your UI-input code can use it however it needs:
if( _map.TryGetValue(key,out var card) )
{
_map.Remove( key );
card.Use();
}
else Debug.LogWarning($"card '{key}' doesn't exists");