- Home /
How can I make a custom Time Range Selector (with sliders)?
I'm trying to use GUI.DrawTexture to create a custom progress bar type object within OnInspectorGUI. Despite the fact that I haven't been able to get it to work outside of OnGUI, I also haven't had luck creating what I want. Basically, I have two sliders that control the range you select. The first would select the opening value of the range, and the second selects the end value. There would then be a texture drawn in between the two that updates with the sliders as you move them. Outside of the range, the texture would be different on each end. Currently, I only have a custom progress bar that fills in from one side working, based on answers from other questions. Is a selector like this possible to create with Unity's API?
Here's my code so far:
var startSliderValue : float = 0.0;
var endSliderValue : float = 1.0;
var pos : Vector2 = new Vector2(20,40);
var size : Vector2 = new Vector2(200,20);
var progressBarEmpty : Texture2D;
var progressBarFull : Texture2D;
function Start() {
progressBarEmpty = Resources.Load("white-texture-large");
progressBarFull = Resources.Load("Black");
}
function OnGUI() { //Ideally, this is OnInspectorGUI in an Editor class
GUI.DrawTexture(Rect(pos.x, pos.y, size.x, size.y), progressBarEmpty);
GUI.BeginGroup(new Rect (pos.x, pos.y, size.x * Mathf.Clamp01(startSliderValue), size.y));
GUI.DrawTexture(new Rect(0, 0, size.x, size.y), progressBarFull);
GUI.EndGroup();
}
The sliders are in a different script within the Inspector.
Answer by Ben Blaut · Feb 27, 2013 at 06:46 PM
To do this, I ended up using EditorGUI.DrawPreviewTexture instead of GUI.DrawTexture. I also used a MinMaxSlider from EditorGUILayout to specify a time range. DrawPreviewTexture draws a dynamic color bar underneath to show where previous time ranges were saved (reading from XML). Since DrawPreviewTexture requires a texture to show, I just initialize my own color textures based on how many time ranges I have with the following function:
/// <summary>
/// Create a texture with a unique color based off of the current
/// _numTimeRanges.
/// </summary>
function createNewTexture(_numTimeRanges : int)
{
var texture : Texture2D = new Texture2D(128, 128);
for (var y : int = 0; y < texture.height; y++) {
for (var x : int = 0; x < texture.width; x++) {
var color : Color;
if (_numTimeRanges == 0) {
color = Color.white;
}
else if (_numTimeRanges % 4 == 1) {
color = Color.red;
}
else if (_numTimeRanges % 4 == 2) {
color = Color.blue;
}
else if (_numTimeRanges % 4 == 3) {
color = Color.yellow;
}
else if (_numTimeRanges % 4 == 4) {
color = Color.black;
}
texture.SetPixel(x, y, color);
}
}
texture.Apply();
}