- Home /
What's the best way to create a gui slider that will change the image on screen?
Basically I am looking for a way to have a 2Dimage displayed on screen, and then use a gui slider that is below it to change that texture?
I.e the slider will have 5 different positions on it that it can be set to that will change it to a different texture.
What would be the best method, to use gui.drawtexture for the texture itself or to have the texture as a plane and make the slider change to a different plane?
What would be the best method for this or if I could be pointed in the right direction.
Thanks
Answer by aaronov · May 08, 2013 at 11:17 PM
You could do something like this:
using UnityEngine;
using System.Collections;
public class example : MonoBehaviour
{
private int textureIndex = 0;
public Texture[] textures;
void OnGUI()
{
textureIndex =
(int)GUI.HorizontalSlider(
new Rect(25, 70, 100, 30),
textureIndex,
0,
textures.Length-1);
GUI.DrawTexture(
new Rect(10, 10, 60, 60),
textures[textureIndex],
ScaleMode.ScaleToFit,
true,
10.0F);
}
}
I'm almost happy with this answer except the magic number "5" in line 16 should be "textures.Length-1". Also you should simply make the textures array public so the user of the script can simply drag as many textures as he wants to the array in the inspector. In this case you don't have to create the array because that's done by the inspector / Unity.
Your suggestions are valid and I'll add them to the answer. I probably should have mentioned I hadn't tested this code :)
Works great! I get a array index out of range error as I am able to move to a 6th position even though I only selected to have 5 textures. I removed the scalemode.scaletofit as it ws messing around with my textures
The index out of range problem is fixed in the answer now. The array length required a 1 subtracted (textures.Length-1).
As for the squashed texture try set the 10.0F value to 0 ins$$anonymous$$d in the DrawTexture function so that the default aspect ratio of the texture is used.