- Home /
Changing a dictionary value from another script
Hi, I'm tring to figure out how to set a dictionary value from another script. I have a GunClass and a InventoryClass. The GunClass handles all shooting mechanics, where the InventoryClass manages the state of the inventory. I keep my inventory items in dictionaries.
In the GunClass I check how many clips (int) I still have left in one of the dictionaries in my InventoryClass, like so:
if (Input.GetButtonDown("Reload"))
{
remainingClips = GameObject.FindGameObjectWithTag("InventoryController").GetComponent<InventoryClass>().playerAmmo[weaponType];
if (remainingClips > 0)
{
Reload();
}
This works fine. Reload() decreases remainingClips by 1. However, I also want to decrease the value in the dictionary itself by 1. I tried to do this by adding this line after Reload():
GameObject.FindGameObjectWithTag("Player Controller").GetComponent<FPSControl>().playerAmmo[weaponType] = remainingClips;
Edit: this is an old snippet: it is supposed to be:
GameObject.FindGameObjectWithTag("InventoryController").GetComponent<InventoryClass>().playerAmmo[weaponType] = remainingClips;
This however, doesn't do anything. I'm unsure how to handle this problem. Any help would be greatly appreciated.
Looks like you're getting the value from one place (playerAmmo dictionary of the InventoryClass component on the "InventoryController" GameObject) and then setting it somewhere else (playerAmmo dictionary of the FPSControl component on the "Player Controller" GameObject). $$anonymous$$aybe you just need to set it in the same dictionary where you got it from?
Woops I copied the wrong code snippet: thats an old version.
GameObject.FindGameObjectWithTag("InventoryController").GetComponent<InventoryClass>().playerAmmo[weaponType] = remainingClips;
Answer by Brokenarrow · Feb 08, 2016 at 12:25 PM
I fixed the problem using a workaround: Instead of changing the value directly, I changed a bool in the target script which adds or changes the dictionary value.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Reference to value type 1 Answer
C# multiple key/value pairs of various types in a single line of code...? 1 Answer