- Home /
Question by
Detinator10 · Aug 01, 2014 at 04:16 AM ·
onguiworldtoscreenpointguibutton
How to have a GUI button be made at the position of it's attached transform?
I am trying to make it so I can make a button wherever I drag the game object to. This is my latest working code:
using UnityEngine;
using System.Collections;
public class ButtonScript : MonoBehaviour {
public Texture2D icon;
public float posX;
public float posY;
public string LevelToLoad;
public int sizeX;
public int sizeY;
Vector3 thisposition;
// Use this for initialization
void Start () {
posX = this.transform.position.x;
posY = this.transform.position.y;
thisposition = Camera.main.WorldToScreenPoint (new Vector3 (posX, posY, 0));
}
void OnGUI()
{
GUI.backgroundColor = Color.red;
if (GUI.Button (new Rect (thisposition.x, thisposition.y, sizeX, sizeY), icon)) {
Application.LoadLevel (LevelToLoad);
}
}
// Update is called once per frame
void Update () {
}
}
the only problem is the Y axis is inverted and I can't figure out how to fix the Y co-ord so it's not inverted. Thanks for any help!
Comment
Best Answer
Answer by robertbu · Aug 01, 2014 at 04:44 AM
GUI coordinates and Screen coordinates are not the same. Both are based on pixels, but GUI coordinates start in the upper left corner and Screen coordinates start in the lower left corner. To fix, insert at line 18:
thisPosition.y = Screen.height - thisPosition.y;
Your answer
Follow this Question
Related Questions
GUITexture on/off using GUILayout.Button 0 Answers
Change GUI.Button Texture on runtime 1 Answer
Problem with UI in iOS / Android 1 Answer
how to make information slideshow? 0 Answers