- Home /
Best way to show variable values on UI
I know I can simply make a bunch of UI texts on a panel and drag each variable one after the other in their respective position, but with how many variables I want to display, I feel as if this approach is way too slow and a waste of time. I have at least 10 of these variables all in the same script and was wondering if there is a much more efficient way of displaying these variables on the player UI without dragging and dropping them over and over again.
Answer by gernomino · May 15 at 12:36 PM
Couple options though don't know that any are really ideal. This is one of the issues I have on a regular basis.
- Could create a prefab with the options set
- Could add a menu item that creates the player and sets any defaults you want. https://docs.unity3d.com/ScriptReference/MenuItem.html
- On the menu item above, you could also create a custom asset in a scriptable object to store the player data for that instance.
It would be cool if you could select assets from multiple folders in Unity and then drag them over all at once, having it apply them to the object in the order you clicked them.
Code example for one of my use cases. Has some of methods 2 and 3 in it.
public class TerrainMenu : MonoBehaviour
{
// Put the item under the existing GameObject/3D Object menu
[MenuItem("GameObject/3D Object/RTS Terrain")]
static void CreateTerrain()
{
// ----- Creating a GameObject in the scene ------ //
GameObject _terrain = new GameObject();
_terrain.tag = "Terrain";
_terrain.layer = LayerMask.NameToLayer("Terrain");
_terrain.name = "Terrain";
GameObjectUtility.EnsureUniqueNameForSibling(_terrain);
// ----- Creating a custom asset and saving it to a file ----- //
// TerrainData inherits from ScriptableObject
TerrainData _terrainData = TerrainData.CreateInstance<TerrainData>();
// Can call any other setup functions you need or set defaults on the scriptable object
_terrainData.Initialize();
// Save to a file
string filePath = AssetDatabase.GenerateUniqueAssetPath("Assets/terraindata.rtsterraindata.asset");
AssetDatabase.CreateAsset(_terrainData, filePath);
// My heightmap is a texture2D so I need to save it separately. Still figuring out how this works.
AssetDatabase.AddObjectToAsset(_terrainData.heightMap, filePath);
// I need to add the script I made to the game object (in your case it would be your player script).
RTSTerrain _script = _terrain.AddComponent<RTSTerrain>();
// Finally I need to tell the script about my asset.
_script.terrainData = AssetDatabase.LoadAssetAtPath<TerrainData>(filePath);
}
}