Before Unity 4.6 new UI system came out, to create a progress bar, the typical process involve writing the OnGUI() function as follows:
public Texture2D emptyProgressBar; // Set this in inspector. public Texture2D fullProgressBar; // Set this in inspector. void OnGUI() { GUI.DrawTexture(Rect(0, 0, 100, 50), emptyProgressBar); GUI.DrawTexture(Rect(0, 0, progress, 50), fullProgressBar); GUI.skin.label.alignment = TextAnchor.MiddleCenter; GUI.Label(Rect(0, 0, 100, 50), string.Format("{0:N0}%",
progress * 100f)); }
This is OK, however not recommended in the new GUI system in Unity 4.6+: you don’t want to mix the GUI with the new and legacy system, right?
Here is the process to create a progress bar using the new UI system:
- Create a new project in Unity3D
- Add a UI Image, name it “Background”, set the sprite to the background image;
- Add another UI Image (or duplicate the above background UI object) , name it “Foreground”, set the sprite to the foreground image;
-
Change the foreground UI image’s Image type to “Filled”, Fill Method to “Horizontal”
- Create a C# script, name it “Progress.cs”, attach it to the foreground UI image:
using UnityEngine; using UnityEngine.UI; using System.Collections; public class Progress : MonoBehaviour { Image foregroundImage; public int Value { get { if(foregroundImage != null) return (int)(foregroundImage.fillAmount*100); else return 0; } set { if(foregroundImage != null) foregroundImage.fillAmount = value/100f; } } void Start () { foregroundImage = gameObject.GetComponent<Image>(); Value =0; }
}
//Testing: this function will be called when Test Button is clicked public void UpdateProgress() { Hashtable param = new Hashtable(); param.Add("from", 0.0f); param.Add("to", 100); param.Add("time", 5.0f); param.Add("onupdate", "TweenedSomeValue"); param.Add("onComplete", "OnFullProgress"); param.Add("onCompleteTarget", gameObject); iTween.ValueTo(gameObject, param); } public void TweenedSomeValue(int val){ Value = val; } public void OnFullProgress() { Value =0;
}
Compile and Run! That is it! Happy coding!
Filed under: Programming, Unity 3d Tagged: 4.6, 5.0, 5.1, 5.x, example, how to, new UI, progress bar, Unity, Unity 3d, using
