- Home /
Is this the best way of using enums?
I'm trying to add categories to my items in an RPG game, so when the UI instantiates it grabs the items category (which I will be assigning to every item's prefab in the inspector) , and then it displays it in the UI under the item's name. Here's what I have so far:
public class itemStats : MonoBehaviour {
public string name;
public enum itemType {
CommonSword,
RareSword,
LegendarySword,
CommonBow,
RareBow,
LegendaryBow,
CommonAxe,
RareAxe,
LegendaryAxe,
CommonStaff,
RareStaff,
LegendaryStaff,
ConsumableItem,
QuestItem,
};
public itemType Category;
public int Damage;
public int Vitality;
public int Energy;
public string category;
void Start () {
if (Category == itemType.CommonSword) {
category = "Common Sword";
}
else if (Category == itemType.RareSword) {
category = "Rare Sword";
}
else if (Category == itemType.LegendarySword) {
category = "Legendary Sword";
}
}
}
And then in the UI script I have this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class itemtypeui : MonoBehaviour {
public Text stats;
// Use this for initialization
void Start () {
stats = GetComponent<Text> ();
//stats.color = new Color32 (255, 195, 0, 255);
stats.text = transform.root.gameObject.GetComponent<itemStats>().category;
//stats.fontSize = 35;
}
// Update is called once per frame
void Update () {
}
}
So it essentially grabs the item's type from the script with the enum on the item prefab and then when the UI instantiates it displays the category it grabbed and prints that string. Just wanted to see if anyone had a better way of doing this. I haven't made a manager before, would this be a time to implement one? How do I assign each gameobject different value for it's variables if I added a manager instead of adding each item stats script to it ?
I'd probably go with a Item Type and Rarity separate, like this.
public enum ItemType
{
Sword,
Axe,
Staff
Chestplate
}
public enum Rarity
{
Normal,
$$anonymous$$agical,
Rare,
Legendary
}
then you can do this
public string category;
public ItemType itemType;
public Rarity rarity;
void SetCategory()
{
category = rarity.ToString() + " " + itemType.ToString();
}
Also, very important. Your items nor your stats should ever be $$anonymous$$onoBehaviours, it is a waste of resources. If you did this because you want to edit the data in the editor, there is much better ways, you should look into EditorWindows, and ScriptableObjects, aswell as just non-Unity class files.
All programmers should be accustomed to creating things for the sole purpose of editing data, in Unity this can be done in EditorWindows, but in normal program$$anonymous$$g we have to create a separate program to edit our data in.