This is how did it - Po-tay-toe/Po-tah-toe.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UnitButton_Script : MonoBehaviour {
private SpriteRenderer rend;
public GameObject defenderPrefab;
public static GameObject selectedDefender;
// Use this for initialization
void Start () {
rend = GetComponent<SpriteRenderer> ();
}
// If you move your mouse inside the button's collider, but DON'T click.
void OnMouseEnter(){
if (!defenderPrefab.Equals (selectedDefender)) {
// Optional condition to check if there are enough resources.
rend.color = Color.grey;
}
}
// If you move your mouse outside the button's collider.
void OnMouseExit(){
if (!defenderPrefab.Equals (selectedDefender)) {
rend.color = Color.black;
}
}
void OnMouseDown(){
// If the correct Defender is already selected, don't bother continuing.
if (defenderPrefab.Equals (selectedDefender)) {
return;
} else {
// transform.parent finds the parent of the current GameObject.
// You can also loop through the transforms of any GameObject with
// children.
foreach (Transform t in transform.parent) {
SpriteRenderer sr = t.GetComponent<SpriteRenderer> ();
if (sr) {
sr.color = Color.black;
}
}
selectedDefender = defenderPrefab;
rend.color = Color.white;
}
}
}
Basically, I changed the script name (note that “Button” is the name of UnityEngine.UI Component, and will generate errors), and when I click on the buttons I loop through the parent’s transform to find any SpriteRenderers and change their colour (ignoring those without).
This works if the Buttons hierarchy is like this:
- Buttons Container
- Background
- Buttons
OR
- Buttons Container
- Background
- Buttons
- Background
BUT it’s easily defeated by having any Buttons outside this “Parent/Child Relationship”:
- Buttons Container
- Background
- Buttons
- Button that won’t work as intended
I also introduced hovering, such that if you enter the button without clicking it, it partially highlights the button, and changes back to normal when the mouse leaves (UNLESS you’re hovering over the currently selected defender, in which case both enter/exit methods are ignored.). This can be easily extended to, say, colour the defender red if there aren’t enough resources?
Finally, I also didn’t bother with the button array because…
I dunno. Laziness?
Thoughts?
