Hi all!
I have a Dictionary parameter in my script with Vector3 type of keys and GameObject values.
Vector3s are used to keep track of the positions of a corresponding GameObject in a scene.
The problem comes when I try to remove the gameobject (and the key). Sometimes the Remove() method doesn’t find the corresponding key even though the value of the key in Dictionary and of the corresponding parameter is the same.
I try to remove the key-value pair like this:
`
public void markDestroyedBallPosition (Vector3 posDestroy)
if (ballsInScene.Remove(posDestroy))
{
removedBallPositions.Add(reducedBalls, posDestroy);
%|-172957788_3|%
}
else
{
}
`
I have debugged this and the value of the posDestroy parameter corresponds to the Key in the ballsInScene Dictionary.
If someone from the community could help, I would appreciate it a lot. I am totally stuck with this bug.
Thanks in advance!
@username
Are you trying to remove a single value or all matching values?
The reason you don’t get a key back when querying on values is because the dictionary could contain multiple keys paired with the specified value.
I wrote this script and i tested value removes using specified key, use RemoveByValue() to remove value against your key.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
private Dictionary<Vector3, GameObject> _dic = new Dictionary<Vector3, GameObject>();
public GameObject value;
// Use this for initialization
void Start () {
_dic.Add(Vector3.back, value);
GameObject someValue = value;
RemoveByValue<Vector3,GameObject>(_dic, someValue);
}
private void RemoveByValue<TKey, TValue>(Dictionary<TKey, TValue> _dic, TValue someValue)
{
List<TKey> itemsToRemove = (from pair in _dic where pair.Value.Equals(someValue) select pair.Key).ToList();
foreach (TKey item in itemsToRemove)
{
Debug.Log(item.ToString());
_dic.Remove(item);
}
}
}