- Home /
C# how to Access UI Assigned to Function
I would like to get a reference to the UI that is assigned and executes a function. Like a button for example. However when Debug.Log(this.gameObject.name); occurs it refers to the gameobject the script is attached to and not the UI. Is this possible or do I have to give my function parameters in order to access the UI element that executes the function?
Well, 'this' keyword means what it means ^^ It means 'on the gameobject the script is attached', you usually don't use it because it is implicit when you call stuff like 'transform.position'.
You want, when you call a function (via a button), that the script that is readed does whatever you want it to do + throwing a debug.log of the name of the object it interacts with ? Do I understand well what you want ?
I think he is after the same principle you get on event listener in .NET
public void $$anonymous$$ethod(object caller, EventArgs e){}
where the first parameter is the caller.
But since you cannot pass object that would be Object.
Answer by Thomas Train · Apr 30, 2015 at 07:13 AM
you can get a reference via GameObject which your UI scirpt attached.
check the below web page first.
http://docs.unity3d.com/ScriptReference/GameObject.GetComponent.html
Answer by fafase · Apr 29, 2015 at 06:45 AM
public void Method(Object obj)
{
Debug.Log(obj.name);
}
You can pass anything that is an Object and anything is an Object in Unity (ok not totally but GameObject and MonoBehaviour). So you can pass the calling Button or Canvas or GameObject holding any of those.
Answer by Soiltest · Apr 29, 2015 at 02:21 PM
Of course like this you have to pass the InputField as a parameter, if you only need this method to assign a value to a string you could just pass the InputField.text as a parameter.
To make your setup work, you have to assign "Scripts" to an object and drag that object in the editor (where you dragged Scripts). You also have to modify slightly your functions, like this:
using UnityEngine.UI; [SerializeField] private InputField _userField; [SerializeField] private InputField _passField;
// Other code.
public void UserInput() { string username = _userField.text; // Code that uses the username variable. }
public void PassInput () { string password = _passField.text; // Code that uses the password variable. } This way you can actually drag the InputFields from the scene hierarchy to the "Scripts" object directly in the editor.
Hope this helps! Regards: Soil Testing Services
Your answer
Follow this Question
Related Questions
Canvas Button OnClick() function arguments 1 Answer
check if part of function is executed in another script 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers