I have a menu with 4 buttons. If the user taps on one, I highlight it to show that it is selected. When the user places the item corresponding to the button in the game scene, the button fades back out.
The problem I am having is that when I have a button selected and then select another button, both buttons are highlighting. The behavior I am trying to achieve is the first button fades when the second button is pressed.
I have tried setting the selectedButton to null, which calls the FadeAll() method from Update(), but both the first and second button clicked remain highlighted. When I click on the game scene, the GameObject corresponding to the latest button press is placed, and all buttons are faded.
Here is my class that controls button fading:
using UnityEngine;
using System.Collections;
public class Button : MonoBehaviour {
public static GameObject selectedButton;
[SerializeField] private GameObject thisButton;
private SpriteRenderer sprite;
private Color originalColor;
private Button[] buttons;
private StarDisplay starDisplay;
void Start () {
starDisplay = GameObject.FindObjectOfType<StarDisplay>();
buttons = GameObject.FindObjectsOfType<Button>();
sprite = GetComponent<SpriteRenderer>();
originalColor = sprite.color;
FadeAll();
}
void Update () {
if (!selectedButton){
FadeAll();
}
}
private void FadeAll(){
foreach (Button button in buttons){
Color fade = sprite.color;
fade.a = 0.5f;
sprite.color = fade;
}
}
void OnMouseDown(){
//TODO error, if select one then select another, both highlight
selectedButton = null;
if (thisButton.GetComponent<Defender>().StarCost <= starDisplay.StarCount){
selectedButton = thisButton;
sprite.color = originalColor;
}
}
}
This is the relevant code from the other class that fades all buttons when one object is dropped into the game scene.
using UnityEngine;
using System.Collections;
public class DefenderSpawner : MonoBehaviour {
private Vector2 targetLocation;
private GameObject parent;
private StarDisplay starDisplay;
private int defenderCost;
void Start () {
starDisplay = GameObject.FindObjectOfType<StarDisplay>();
parent = GameObject.Find("Defenders");
if (!parent){
parent = new GameObject("Defenders");
}
}
void OnMouseDown(){
targetLocation = CalculateWorldPointOfMouseClick(Input.mousePosition);
if (Button.selectedButton){
defenderCost = Button.selectedButton.GetComponent<Defender>().StarCost;
if (starDisplay.UseStars(defenderCost)){
GameObject defender = Instantiate(Button.selectedButton, targetLocation, Quaternion.identity) as GameObject;
defender.transform.parent = parent.transform;
Button.selectedButton = null;
} else {
print("Cannot afford defender");
}
}
}
In the second class, all buttons fade when the selected Button == null. But in the first class this is not happening when I set selectedButton = null in OnMouseDown(). Any ideas for another way to go about this would be greatly appreciated!