I am building a game in unity and I need a certain event to be fired when the game object reaches a certain point with user input. is there any way to do it in c#
For example, in javascript, we can add the click() function which fires that on the click function. Is there a way to do it in c#
CodePudding user response:
There's an example from Unity Documentation here: https://docs.unity3d.com/2019.1/Documentation/ScriptReference/UI.Button-onClick.html
Example.cs
using UnityEngine;
using UnityEngine.UI;
public class Example : MonoBehaviour
{
//Make sure to attach these Buttons in the Inspector
public Button firstButton, secondButton, thirdButton;
void Start()
{
//Calls the TaskOnClick/TaskWithParameters/ButtonClicked method when you click the Button
firstButton.onClick.AddListener(TaskOnClick);
secondButton.onClick.AddListener(delegate { TaskWithParameters("Hello"); });
thirdButton.onClick.AddListener(() => ButtonClicked(42));
thirdButton.onClick.AddListener(TaskOnClick);
}
void TaskOnClick()
{
Debug.Log("You have clicked the button!");
}
void TaskWithParameters(string message)
{
Debug.Log(message);
}
void ButtonClicked(int buttonNo)
{
Debug.Log("Button clicked = " buttonNo);
}
}
Of course, Example.TaskOnClick()
could be called manually from other places in code & not only when the button is clicked.
CodePudding user response:
Separate code from onClick method to another method. Then you can call the method when you want.
// METHOD TO CALL WHEN CLICKED
public void onClickMethod(){
method();
}
private void method(){
/* CODE HERE */
}
// EXAMPLE
void Update(){
if(ex > 5) method();
}
I didnt use Unity3D last time. I guess you can't just call onClickMethod()?