you can compact things into a single “if input e” and I’d probably go with a switch statement
if (Input.GetKeyDown(KeyCode.E))
{
switch (GameobjectTag )
{
case "myTag1":
// stuff
break;
case "myTag2":
// other stuff
break;
default:
// stuff if it's totally the wrong tag!
break;
}
}
I would use a collection. A dictionary seems well suited to the problem
public GameObject theGameObject;
public string theTag;
Dictionary <string, int> items = new Dictionary <string, int>();
void Update() {
if (Input.GetKeyDown(KeyCode.E)) {
theGameObject.SetActive(false);
if (items.ContainsKey(theTag){
items[theTag] = items[theTag] + 1;
} else {
items.Add(theTag, 1);
}
}
}
That said your way of handling the GameObject and string at the top of your script is pretty odd. Its likely to be prone to bugs down the track. I would suggest implementing raycasting inside of your if statement to figure out what the GameObject should be.
Yes, I agree, a dictionary is the way to go. I would also add, you should put this into a function with a good name that describes what you are doing.
Example:
public const UnityEngine.KeyCode KEYBIND_GET_ITEM = KeyCode.E;
Dictionary<string, int> Inventory = new Dictionary<string, int> {
{ "Wooden Planks", 0 },
{ "Log", 0 },
{ "Half Log", 0 }
};
void Update()
{
if (Input.GetKeyDown(KEYBIND_GET_ITEM))
{
AddToInventory(gameObject);
}
}
void AddToInventory(GameObject go)
{
if (Inventory.ContainsKey(go.tag))
{
// go is a gameObject that has a tag of 'Wooden Planks', 'Log', or 'Half Log'.
Inventory[go.tag] += 1;
go.SetActive(false);
}
}
There is now a new function, ‘AddToInventory’, whose name more clearly conveys what is happening.
In your original example, you have a variable called ‘WoodenPlanks’, and an object tag ‘WoodenPlank’. This spelling difference will bite you in the future. You can avoid providing redundant information, by setting it up like above. This provides the pleasing benefit of being able to use spaces in the item name now, and automatic tag checking, which prevent non-inventory tags from being processed.