- Home /
How to center the score in screen?
Hello,
I put the score at upper center of the screen. Score is increased by players performance. What i want to do is, to center the score as far as it's number. For example, if score is greater than 9 or 99 or 999, it should stay in the upper center of the screen. I centered it by 0. It goes right as far as it's number. If it's greater then 9, it goes right.
I could do that just like that;
if(Score >= 10)
{
GUI.Label(new Rect(100, 10, 100, 20),"",skin.GetStyle("Score"));
}
if(Score >= 100)
{
GUI.Label(new Rect(90, 10, 100, 20), "",skin.GetStyle("Score"));
}
if(Score >= 1000)
{
GUI.Label(new Rect(80, 10, 100, 20), "",skin.GetStyle("Score"));
}
but i didn't want to do it like that. I was wondering that, if there is another way to do it briefly and to the point. It should stay in the top center all the time but how?
Answer by HarshadK · Oct 09, 2014 at 11:55 AM
Use GUIStyle.CalcSize to calculate the size of content from your label and then re-draw it according to its size.
Damn.. it's Javascript. I guess i need to find it's C# version. Is this the only way?
The example is incomplete, but here is the c# version. be aware of the fields being modified on the target Property(damage and armor).
using System;
using System.Collections;
using UnityEditor;
[CustomEditor(SimpleExampleScript)]
public class CustomEditorExample : Editor
{
public void OnInspectorGUI()
{
target.damage = EditorGUILayout.IntSlider("Damage:", target.damage, 1, 100);
ProgressBar(target.damage / 100.0f, "Damage");
target.armor = EditorGUILayout.IntSlider("Armor:", target.armor, 1, 100);
ProgressBar(target.armor / 100.0f, "Armor");
}
public void ProgressBar(float value, string label)
{
Vector2 size = GUI.skin.GetStyle("ProgressBarText").CalcSize(GUIContent(label));
Rect rect = GUILayoutUtility.GetRect (size.x, $$anonymous$$athf.$$anonymous$$ax(size.y));
rect = new Rect(rect.x + 4, rect.y, rect.width - 8, rect.height);
EditorGUI.ProgressBar (rect, value, label);
EditorGUILayout.Space();
}
}
I tried to modify this but i couldn't. How can i modify this?
I have made the shortest way to center the score. Here is what i did;
skin.GetStyle("Score").alignment = TextAnchor.UpperCenter;
Vector2 contentOffset = skin.GetStyle("Score").contentOffset;
contentOffset.x = -151;
skin.GetStyle("Score").contentOffset = contentOffset;
These codes centers the score according to its number.
Thanks for interesting guys, appreciated!