- Home /
change onclick function via script
First of all I want to tell that I saw lots of related posts and I didn't get it at all !!!! so do not delete this post and don't post links for me :).
so I have a button with no OnClick function. how can I place this script in that button via script? can anyone tell me?for example if player Collides with an object .then this code places in an OnClick function of a button.
public void Test(){
Debug.Log ("testttt");
}
watch this ,it's a short video about what I want. https://streamable.com/a0tq3
any tutotrial or whatever .....
Answer by pako · Jan 01, 2018 at 03:53 PM
The UI.Button has an onClick event that gets triggered whenever the button is clicked.
Normally, you'd just add a listener (point to a method) to run when the button gets clicked, in Awake()
or Start()
, like this:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class ClickExample : MonoBehaviour
{
public Button CustomButton; //drag-n-drop the button in the CustomButton field
void Awake()
{
CustomButton.onClick.AddListener(CustomButton_onClick); //subscribe to the onClick event
}
//Handle the onClick event
void CustomButton_onClick()
{
Debug.Log("testtttt");
}
}
However, in your case, you want to handle the event only under certain conditions, i.e. if the player collides with an object. To do this, you'll still use most of the above code, but also make sure that the event is not handled if a collision doesn't take place.
So, you could add a conditional statement and use a Boolean.
//Handle the onClick event Conditionally
void CustomButton_onClick()
{
if(hasCollided) //set hasCollided = true when the player collides with object, and reset to false at an appropriate place.
{
Debug.Log("testtttt");
}
}
Alternatively, subscribe/unsubscibe the event handler to the event in suitable places, instead of Awake()
or Start()
. For example:
private void OnCollisionEnter(Collision collision)
{
CustomButton.onClick.AddListener(CustomButton_onClick);
}
private void OnCollisionExit(Collision collision)
{
CustomButton.onClick.RemoveListener(CustomButton_onClick);
}
Let me know if you need any clarifications.
Very helpful examples!
Just to clarify for future viewers, the "GetComponent()" part is unnecessary, as CustomButton is already a reference to the Button component.
hehe, I really don't know what I was thinking when I did this, but it's funny you're the only one within 2.5 years to notice and comment about it! :-) In fact, the local btn variable is redundant too. I edited my response to make the usage clearer. Thanks!
Your answer
Follow this Question
Related Questions
UI bugging after build? 0 Answers
Enemy Select 1 Answer
How to constantly add force to my player when a button is hold? 2 Answers
Moving camera around with GUI buttons 4 Answers