Postion GUI Texture in the center when called?

My script is working how i wanted it except one issue, when it does call the GUI Texture i have to manually Position GUI Texture, or if i move the object in the world it will mess up and appear in different Positions…

I have it setup so when the player walks up to the object and presses action it appear, but it’s not centered if i move the Parent Object at all…

Here is the part that calls it On/Off, how do i Position it?
I can Position the label just not the texture.

function OnGUI(){
    var read = new Rect(Screen.width*0.5,Screen.height*0.5 - 200, 250, 80);
    if (enter){
    GUI.Label(read, "Press (E) To Read");
    }
    
    if(Input.GetKeyDown("e") && enter){
    if (!audio.isPlaying){
    ///var Page = new Rect(Screen.width*0.5,Screen.height*0.5);
    audio.Play();
    linkedPage.SetActiveRecursively( !linkedPage.active );
    }
}
}

1 Answer

1

GUITextures live in Viewport space where the lower left of the screen is (0,0), and the upper right is at (1,1). They don’t live in world space. The easiest fix for this problem would be to unparent the GUITexture. Then you can use Camera.WorldToViewportPoint() to position the object. In some situations the following will work with parented GUITextures:

#pragma strict

function Update() {
	transform.position = Camera.main.WorldToViewportPoint(transform.parent.position); 
}

Yeah it says: NullReferenceException I tried it as a child as it was, then un-paranted it but still it's way off the screen, or cut off at the bottom. I use the same script to call every page, i added it to the update on my script. function Update () { transform.position = Camera.main.WorldToViewportPoint(transform.parent.position); if (Input.GetKeyDown("e") && enter) { The label appears where ever the main object is (script is on) but the texture is all messed up x,y yadda yadda.

I think i might have found a solution for it. I clicked each GUI Texture and set the Position to: X 0.5, Y 0.5, Z 0.5 and Pixel inset: Y 2, X 2 I tried it the page appears in the center. so i moved the Parent Object down+over, and tried again and it's still centered. But if i child them, it is really messed up. So i will have to do it the hard way i guess? one by one every time i make a new page.