- Home /
Change value of integer based on string input in a separate script
So I'm trying to make some sort of inventory.
There are two scripts, first changeInv.cs :
public class changeInv : MonoBehaviour {
public void addInv(string item){
GameObject inv = GameObject.FindWithTag("Inventory");
inv.GetComponent<Inv>().item++;
}
public void removeInv(string item){
GameObject inv = GameObject.FindWithTag("Inventory");
inv.GetComponent<Inv>().item--;
}
}
and Inv.cs :
public class Inv : MonoBehaviour {
public int solarPanel = 0;
public int crops = 0;
}
What I'm trying to do is call for example addInv("crops") so that crops integer in Inv.cs is increased by 1.
I'm getting the error "error CS1061: Type Inv' does not contain a definition for
item' and no extension method item' of type
Inv' could be found"
What should I do?
Answer by Jamora · Jun 20, 2013 at 10:28 PM
You can't do what you're trying to do like that. Instead, consider using a Dictionary, which maps item names to the quantity currently carried. Additionally, I see no point in having the inventory code spread out among two classes. So here is how I would do the inventory you are attempting.
using UnityEngine;
using System.Collections.Generic;
public class Inventory : MonoBehaviour {
private Dictionary<string,int> inventory = new Dictionary<string,int>();
public void addItem(string item){
if(inventory.ContainsKey(item))
inventory[item]++;
else
inventory.Add(item,1);
}
public void removeItem(string item){
if(inventory.ContainsKey(item) && inventory[item] > 0)
inventory[item]--;
}
}
Your answer
Follow this Question
Related Questions
C'# When Taking Variables From Other Scripts, The Values Do Not Update 1 Answer
C# How do I reference a variable from one script in another script 2 Answers
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Distribute terrain in zones 3 Answers
Can't access Depth of Field? 2 Answers