I am trying to add an Input Field for the Player to enter a door code to unlock the door.
I have a test scene with a cube as the door, a cube as Player
, Canvas, Input Field and Plane.
In the Inspector I can see Input Field named MyIn, with a component Input Field which contains a Text field .
When the game runs I can see the text entered in the field in the Inspector.
In the door control script I have a collider script
public class Targetscrip : MonoBehaviour {
void OnTriggerEnter(Collider col) {
Debug.Log ("trigger");
var go = GameObject.Find("MyIn");
var inp = go.GetComponent ("Input Field");
Debug.Log (inp);
var txt = go.GetComponent ("Text");
Debug.Log (txt);
}
}
I thought I could go one step at a time to get the value.
debug log shows “trigger” “Null” and “Null”
Can anyone tell me what I am doing wrong ?
I would appreciate an actual answer rather than suggestion to tutorials. I am trying to follow tutorials and getting nothing working. tons of error codes about deprecated code.
Thanks
Yo man I don’t think Input fields are GameObjects. Dont do all this finding anyway. Make a public InputField variable to store the reference to the input field and just drag it in through the inspector.
I have also tried declaring a static variable in the input script and accessing it by using Scriptname.variable but that just gives me an error.
why not declare the variables in the start? I don’t get the whole “var” bit. I am new at this as well but learned totally different
public GameObject go;
private Text text;//or make it public and you don't need the line in the start function
void Start(){
text = go.GetComponent<Text>();
}
void OnTriggerEnter(Collider col){
Debug.Log("text");
}
}
}
var inp = go.GetComponent (“Input Field”);
Class names can’t have spaces in them so this can’t work. I recommend always using the generic version of GetComponent, which prevents this kind of misspelling mistakes.
using UnityEngine.UI;
...
var inp = go.GetComponent<InputField>();
Only use the string version if the component you want to get needs to change dynamically or if you have some other goood reason for it.