Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

[Unity - JavaScript] How to move a textfield

Discussion in 'Scripting' started by MrRwstudios, Oct 4, 2014.

  1. MrRwstudios

    MrRwstudios

    Joined:
    Oct 4, 2014
    Posts:
    2
    So, I'm sort of new to scripting, and I need some help to move a GUI.TextField I scripted. It is currently stuck in the corner of the screen and I want to move it to the middle.

    Code:

    var stringToEdit = "Player1"; var userHasPressedEnter;
    function OnGUI () { GUI.Label (Rect (20, 20, 200, 60), "Enter Name:");
    stringToEdit = GUI.TextField (Rect (240, 40, 600, 100), stringToEdit, 40);
    }

    if(userHasPressedEnter == true) {

    }

    else {

    }
     
  2. aoe_labs

    aoe_labs

    Joined:
    Nov 4, 2013
    Posts:
    42
    Please use the code editor when pasting code.

    Anyhow, in order for the an element to be in the center, in your case the TextField, change the position parameters of the Rect to use the Screen class's width and heigh properties, like so:

    Code (JavaScript):
    1. stringToEdit = GUI.TextField (Rect (Screen.width / 2, Screen.height / 2, 600, 100), stringToEdit, 40);
    Dividing by 2 puts it in the center, but it's still shifted a bit as a result of the width and height of the TextField. Try pasting the above code and you'll see what I mean. To fix this, you will also want to subtract the half of the respective width and height of the TextField itself
    Code (JavaScript):
    1. stringToEdit = GUI.TextField (Rect (Screen.width / 2 -300, Screen.height / 2 - 50, 600, 100), stringToEdit, 40);
     
    Last edited: Oct 4, 2014