- Home /
Changing Color of Material with Bool and Unity UI
So I am running in to a weird problem using Unity UI system in the Inspector. What I want to do is to be able to press the Move Or Attack button and have the highlights over the tiles respond so that when the player presses the Move button, the tiles change color to blue and when they press the Attack button the tiles change to red. The color change will only happen when the mouse is hovering over the tiles. On mouse exit they are clear. I thought that this would work.
public class ClickableTile : MonoBehaviour {
//private UnitMovement unitActions = new UnitMovement ();
public int tileX;
public int tileY;
public TileMap map;
public bool characterisString;
public bool attacking;
public bool moving;
void Start()
{
characterisString=true;//unitActions.moving=true;
}
void OnMouseUp()
{
Debug.Log ("Click");
map.MoveSelectedUnitTo (tileX, tileY);
}
void OnMouseEnter() {
if (moving=true) {
transform.GetComponent<Renderer>().material.color = Color.blue;
Debug.Log("Blue");
} else if (attacking=true) {
transform.GetComponent<Renderer>().material.color = Color.red;
Debug.Log("Red");
}
//Debug.Log("my position is (" + gridPosition.x + "," + gridPosition.y);
}
void OnMouseExit()
{
transform.GetComponent<Renderer>().material.color = Color.white;
}
public void AttackButton()
{
if (!attacking) {
moving = false;
attacking = true;
} else {
moving = false;
attacking = false;
}
}
public void MoveButton()
{
if (!moving) {
moving = true;
attacking = false;
} else {
moving = false;
attacking = false;
}
}
}
However, what ends up happening is that the color of the tiles just stay as blue.I currently have the AttackButton attached to the OnClick() for the Attack button and the MoveButton() attached to the OnClick() for the Move Button. Here is a screen shot of the scene.
http://gyazo.com/563cf0a0ad3155d46ddcf212a090b901
If any one can help me out, I would greatly appreciate it.
Answer by allenallenallen · Aug 06, 2015 at 06:27 AM
Think about how the whole process should execute first.
Mouse enters tile
Mouse click
Registers as attacking or moving or whatever
But the way you do it is like this.
Mouse click
Registers as attacking or moving or whatever
Mouse enters tile
You see the order is wrong.
When you do OnMouseEnter, you haven't decided on whether the player is attacking or moving yet so it won't work.
So in order to fix this:
I suggest you delete OnMouseEnter because you don't need it. Instead, put everything in OnMouseEnter to MoveButton before the if statements.
public void MoveButton()
{
if (moving=true) {
transform.GetComponent<Renderer>().material.color = Color.blue;
Debug.Log("Blue");
} else if (attacking=true) {
transform.GetComponent<Renderer>().material.color = Color.red;
Debug.Log("Red");
}
//Debug.Log("my position is (" + gridPosition.x + "," + gridPosition.y);
if (!moving) {
moving = true;
attacking = false;
} else {
moving = false;
attacking = false;
}
}