- Home /
Simple button script help
I'm trying to make a button that will activate an image on the first click and deactivate it if clicked again. I don't understand how to make custom scripts for buttons, what is a simple script that will achieve this and how to i attach the image i want activated? I'm coding in c#
Answer by alexi123454 · Jul 22, 2015 at 07:13 PM
All you would have to do is make a script with a boolean variable, and a function for the button to use. Something like this:
bool showImage = false;
public GameObject displayImage;
public void ToggleButton()
{
showImage = !showImage ;
}
void Update()
{
if (showImage)
{
displayImage.SetActive(true);
}
else
{
displayImage.SetActive(false);
}
}
If you're using the new unity UI (with a Canvas), you can make the UI button call the "ToggleButton" function by scrolling down to the "OnClick" list, drag in whatever gameObject has this script on it, and then point it at at the correct function. Also, make sure to assign the displayImage variable from the editor.
If you're using the old unity OnGUI system, just wrap the button with an if statement, and inside call the ToggleButton() function from inside the if statement.
I've copied this into my script and added the script to the image, then dragged the image into the onclick list and selected the toggle button function. Nothing happens when I click the button still, and I don't know enough about coding to figure out why.
This script has to be on something other than the image, because it's setting the gameObject to inactive when the image isn't being shown. If the game object is inactive, then the scripts on it don't get updated. Place this script on the button, and that should help.
Also, don't forget to the assign the "displayImage" variable to the image.
Answer by ToyoEmpire · Jul 23, 2015 at 12:51 AM
Hello TempestInATeacup
Searching for function Button click on C#
this a simple code to make a click and show an image, just make a new scene for image and you need to make a button again in Image scene with transparency set to 0
this tutorial will help you
https://www.youtube.com/watch?v=kQ2Qc_0MIyI
hope it help you :)