- Home /
How do you set a string while in game ?
Wagwan ,
I want the player to set a string while in the game and then to save it to PlayerPrefs but I'm not sure on how to prompt the player to do this and how to display a text box to write it in ? Could somebody offer advice ?
Thanks Stealth
Answer by sarcasteak · May 07, 2014 at 04:31 PM
See this:
var stringToEdit : String = "Hello World";
function OnGUI () {
// Make a text field that modifies stringToEdit.
stringToEdit = GUI.TextField (Rect (10, 10, 200, 20), stringToEdit, 25);
}
http://docs.unity3d.com/Documentation/ScriptReference/GUI.TextField.html
Answer by Dazdingon · May 07, 2014 at 06:01 PM
alternative method (not using OnGUI)
Use this code to get input from the player : public var displayText : String = "";
function GetInputText () {
//Get characters one by one from input
for(c in Input.inputString){
//Ignore multi-line input
if(c == "\n"[0] || c == "\r"[0]){
continue;
}
//Handle backspase manualy
if(c == "\b"[0]){
if(displayText.Length > 0){
displayText = displayText.Substring(0, displayText.Length - 1);
}
}
//Add character recieved from input
else{
displayText += c;
}
}
}
You can then display the text with something like this : public var displayObject : TextMesh;// or GUIText
function DisplayText () {
displayObject.text = displayText;
//Add a blinking text cursor for fun
if(Time.time % 1 > 0.5)displayObject.text += "_";
}
This works with both TextMesh(3DText) and GUIText
Save displayText into your PlayerPrefs (e.g. when enter is pressed)