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.
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: