I am working on a game which is mainly UI based (all elements on screen are part of a canvas (or more)). My player has ~25 stats (ints, floats and strings) and has items which also have about 10 stats each.
The stats are pulled from the server on login and stored in lists and dictionaries.
My question is:
To display these in TEXT fields in the UI, I have to declare dozens of public TEXT fields and then manually assign the text field corresponding to each variable in the Inspector.
As you can imagine, this is a long process and leaves room for a lot of errors (mainly reference not set to instance of variable).
Is there a better way to display these variables on screen? I’m happy to research how to implement a certain technique if you tell me the name of it or if you’re feeling particularly kind, code snippets are also appreciated.
If declaring dozens of public text fields and assigning them in the editor is the best way, I’ll go about it that way. But didn’t want to start implementing that only to find there was a more performance friendly way.
The way I’d do this is to define a manager class that specifically handles the UI. This would include a public method to find the text fields, which you could then call from an Editor class. Here’s a brief snippet:
using UnityEngine;
using UnityEngine.UI;
public class UIManager: MonoBehaviour {
public Text healthField;
public void GatherElements()
{
// find the "Health Field" GameObject, and get it's Text Component
healthField = GameObject.Find("Health Field").GetComponent<Text>();
}
// set the value of the "Health Field" text
public void SetHealthFieldText(int newHealth)
{
healthField.text = string.Format("Health: {0}", newHealth);
}
}
The Editor class might look something like the following:
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(UIManager))]
public class UIManagerEditor: Editor()
{
public override void OnInspectorGUI()
{
// "target" is an Object by default, so cast it to a UIManager here
UIManager manager = (target as UIManager);
if (GUILayout.Button("Gather UI Elements")
{
manager.GatherElements();
}
}
}
I was not aware of the Editor Class. Reading up on it in the Unity Documentation, it might be just what I was looking for. I will go thorugh it in depth and hopefully it will work for my case! Many thanks for your reply, Philip!