button UI event/functions
Clicking Buttons and having things happen.
So, you're able to drag objects and create UI events in the Inspector..but I think this type of scripting is perhaps a bit quicker/precise?
Code was lifted from the official Unity page.
Make 3 button UI objects and add this script to an empty gameobject/or anything.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class button_tut : MonoBehaviour
{
public Button _firstButton, _secondButton, _thirdButton;
//public Camera _cam;
public GameObject _cube;
// Start is called before the first frame update
void Start()
{
//setup various listener function things on the "onclick", per 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've clicked a button!");
_cube.transform.localEulerAngles += new Vector3(0, 19, 0);
//here we print to the debug, as well as add a value to the _cube object's rotation.
//note that the third button is also calling this function, as well as the ButtonClicked function
}
void TaskWithParameters(string message)
{
Debug.Log(message);
}
void ButtonClicked(int buttonNo)
{
Debug.Log("Button clicked = " + buttonNo);
}
}
Comments
Post a Comment