- Home /
i want my star () function to work my button is clicked
it is working fine, but I want is to display message when button is clicked
using UnityEngine; using System.Collections; using UnityEngine.UI;
public class OnClick : MonoBehaviour {
public Button button;
void Update () {
this.star ();
}
void star() {
if (GetComponent<Image> ().color == button.GetComponent<Image>().color)
{
Debug.Log("Hello");
}
}
}
Answer by Addyarb · May 03, 2015 at 06:11 PM
I'm assuming you are using the new Unity 4.6+ uGUI system. It can be a bit confusing at first, so I suggest you read over the overview for the new GUI system.
To answer your question, there are a few steps you must take in order to get this working.
Change
void star
topublic void star
This will allow us to access that function from a different object, which we'll need to do in order to map that function to a UI button.Create a Canvas
Right-Click the canvas GameObject, hover over "Create," and then "UI," and then "Button."
Now that we've got our button, we need to open up a slot for that script to go in. Do this by clicking your button GameObject, scroll down in the inspector, and find the "Button" component.
Now, click the "+" button under the "On Click" area. This will open up a slot with 3 fields. The first is asking when it should be active, the second is asking what GameObject the script whose function you want to trigger is on, and the last is a drop-down menu that allows you to select the function. The drop-down menu will become unlocked/ungreyed as soon as we drop the appropriate GameObject in.
Drag your GameObject that your script is attached to into the empty field on your new OnClick function.
Click the drop-down menu, find the name of your script (your script name is "OnClick" in this case).
Now, hover over your script name, and find the name of your function (yours is called "star" in this case).
Good luck with your game!
thanks Addyarb
but now it is saying "NullReferenceException: Object reference not set to an instance of an object OnClick.star () (at Assets/New Folder/scripts/OnClick.cs:20) OnClick.Update () (at Assets/New Folder/scripts/OnClick.cs:11)"
please help
Please post your entire script here, and perhaps underline the line that Unity goes to when you double-click the error in the console.
Thanks!
Your answer
Follow this Question
Related Questions
Why won't my function show up in the onClick area of a button? 2 Answers
[Solved] Button OnClick properties are missing after loading the scene 4 Answers
Passing through a GameObject/Function to a button's OnClick 1 Answer
Adding onClick listener to an array of buttons 1 Answer
List of Eventlisteners to add to a Button on demand? 0 Answers