Getting a KeyNotFoundException just trying to access a dictionary...any ideas?

I’ve got a dictionary setup with some key, value pairs and I just want to be able to access them with a function, but I’m getting this error when I call my showPotion() function (see below):

KeyNotFoundException: The given key was not present in the dictionary.

Here’s how my script looks:

#pragma strict
import System.Collections.Generic;

var potions = new Dictionary.<String, int>();

function showPotion(potionName:String) 
{
	Debug.Log(potions["Hea1PoInt"]);
}

function Start () {

var potions = new Dictionary.<String, int>();
potions.Add("Hea1PoInt", 0);
potions.Add("Hea2PoInt", 3);
potions.Add("Hea3PoInt", 0);
potions.Add("Hea4PoInt", 0);
potions.Add("Hea5PoInt", 0);
}

I’m stumped! Can anyone shed some light on this? Thanks!

You created a new local variable named potions in your Start function that hides your public one implemented at the class level.

On a more general note - you can use ContainsKey or TryGetValue to avoid circumstances where the key might not be in the Dictionary but you don’t want to bomb out or put up with the overhead of a try-catch block.

Oh god…I’ve been looking at this for an hour and didn’t see that old potions variable!! Thank you, I knew it would be something silly I did :slight_smile: