- Home /
Changing GUITexture's position through code (relative to screen)
I'm trying to change a GUITexture's position (on the x axis) through code upon keyboard input. I can't seem to be able to change the guiTexture's pixelInset's X position for some reason. Here's some code for you to further investigate:
using UnityEngine; using System.Collections; public class GUITextureScript : MonoBehaviour { public GUITexture texture; bool menuOut; // Use this for initialization void Start () { menuOut = false; texture.guiTexture.pixelInset = new Rect(0, 0, 1, 1); } // Update is called once per frame void Update () { if (Input.GetKeyDown ("m")) { showMenu (); } } void showMenu() { Debug.Log ("Button M"); if (!menuOut) { //texture.guiTexture.pixelInset.x += 10; menuOut = true; } else { //guiTexture.pixelInset.x -= 10; menuOut = false; } } }
Answer by Brett Sim · Mar 21, 2013 at 08:29 PM
Found it. pixelInset must always be reset as a new Rect variable in order for the changes to apply. Here's the end result:
using UnityEngine;
using System.Collections;
public class GUITextureScript : MonoBehaviour
{
public GUITexture texture;
bool menuOut;
// Use this for initialization
void Start ()
{
menuOut = false;
texture.guiTexture.pixelInset = new Rect(600, 0, 1, 1);
}
// Update is called once per frame
void Update ()
{
if (Input.GetKeyDown ("m"))
{
showMenu ();
}
}
void showMenu()
{
float texPosY = texture.guiTexture.pixelInset.y;
float texWidth = texture.guiTexture.pixelInset.width;
float texHeight = texture.guiTexture.pixelInset.height;
if (!menuOut)
{
texture.guiTexture.pixelInset = new Rect(400.0f, texPosY, texWidth, texHeight);
menuOut = true;
}
else
{
texture.guiTexture.pixelInset = new Rect(600.0f, texPosY, texWidth, texHeight);
menuOut = false;
}
}
}