- Home /
How to make a button script.
I'm using Unity 4.6, and and very new to Unity.
So I created a UI in the editor, and now I want to add some functionality to the buttons in that UI. I've created a C# script and attached it to the relevant button object, but I'm not sure how to call a specific C# function when the button is clicked.
I've done some googling, and decided that OnGUI was the way to go... But using OnGUI triggers even if I click nowhere near the attached button.
I've done some more googling, and decided that what I want is to implement OnMouseUpAsButton, but now nothing seems to happen when I click the button.
Here is my code, if you're interested. using UnityEngine; using System.Collections;
public class btnPlay : MonoBehaviour {
private float startTime = 0.0f;
private float animDuration = 0.5f;
private bool animated = false;
private float startAngle = 0.0f;
private float endAngle = Mathf.PI / 4;
private float Z = 0;
private float M = 0;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (animated) {
float currentTime = Time.realtimeSinceStartup;
if (currentTime - startTime > animDuration) {
Camera.main.transform.position = new Vector3(M * Mathf.Cos(endAngle), M * Mathf.Sin(endAngle), Z);
animated = false;
}
// Transform
float dt = (currentTime - startTime) / animDuration;
float theta = (endAngle - startAngle) * dt + startAngle;
Camera.main.transform.position = new Vector3(M * Mathf.Cos(theta), M * Mathf.Sin(theta), Z);
}
}
void OnMouseUpAsButton () {
startAngle = Mathf.Atan2(Camera.main.transform.position.y, Camera.main.transform.position.x);
Z = Camera.main.transform.position.z;
M = Mathf.Sqrt(Mathf.Pow(Camera.main.transform.position.x, 2) + Mathf.Pow(Camera.main.transform.position.y, 2));
startTime = Time.realtimeSinceStartup;
animated = true;
}
}
Any help would be very appreciated.
Answer by AyAMrau · Aug 30, 2014 at 06:59 PM
If you are using the new UI, the Event System handles catching the events (such as clicking).
All you need to do is add a functionality to the button.
Can you provide a functional or $$anonymous$$imal example of it in action? I've tried the stuff in that link, but that code won't compile. It complains about the type 'Button' not being found.
Couple of reasons why it might not find the type.
You need to include the UI in your using or import statements at the top of your script
Your not using the beta version of Unity 4.6
Your answer
Follow this Question
Related Questions
What is frame, How OnGuI is called every frame? 2 Answers
What Am I Doing Wrong? Variable Names 3 Answers
Inputing an Equation 0 Answers
How to dynamically change the text in Unity(Augmented Reality + NYARtoolkit(C#)) ? 0 Answers
The name 'Joystick' does not denote a valid type ('not found') 2 Answers