Unity: Un-even progress bar
One afternoon at the DADIU production, I was assigned the task of creating an un-even progress bar for the game (Branch) [branchgame.com].
Having searched the documentation and forum, I didn’t see an easy way to do this posted anywhere.. thus this post.
The idea is having image A as a background to image B, which is the fill. Then, calculating the percentage of image B which needs to be filled and using Unity’s ScaleMode.ScaleToFit when drawing image B on top of A, the desired effect can easily be achieved. An example can be seen in the image below.
The code for the GUI can be seen below, and a unitypackage with the example can be found here [jbmadsen.com].
using UnityEngine;
using System.Collections;
public class GUIMask : MonoBehaviour
{
public Texture2D tex = null;
public Texture2D texOver = null;
private Rect texRect;
private Rect texOverRect;
private int texWidth = 200;
private int texHeight = 200;
private int counter = 0;
public void Start()
{
texRect = new Rect(Screen.width - texWidth - 10, 10,
texWidth, texHeight);
StartCoroutine(Counter());
}
private IEnumerator Counter()
{
while (counter < 100)
{
counter++;
yield return new WaitForSeconds(0.2f);
}
}
public void OnGUI()
{
if (tex == null || texOver == null) return;
GUI.DrawTexture(texRect, tex);
if (counter >= 1)
{
int tempTexHeight = (int)Mathf.Min(counter * texHeight / 100,
texHeight);
texOverRect = new Rect(
Screen.width - texWidth - 10,
10 + texHeight - tempTexHeight,
texWidth,
tempTexHeight
);
GUI.BeginGroup(texOverRect);
GUI.DrawTexture(new Rect(
0,
-(texHeight - tempTexHeight),
texWidth,
texHeight),
texOver,
ScaleMode.ScaleToFit
);
GUI.EndGroup();
}
}
}

