I’m creating a grid system and allowing players to utilize multiple units to put furniture. The problem is, I have a script that is not working the way I intend:
- Units hovered over change material color to red
- Units that are clicked are saved in a list
- All units saved in the list are changed to blue
I have 1 and part of 2 finished. The problem is with 2, it seems like only one item is being saved. And when I run 3, the colors do not change at all.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class GridUnitScript : MonoBehaviour {
public Vector3 originalPos;
public Vector3 currentPos;
public GameObject GridUnit;
public Rect selectionBox;
public List<Collider> unitsClicked = new List<Collider>();
void selections() {
}
void Start () {
//Change all color of units to Gray. Replace this with material later on.
GetComponent<Renderer>().material.color = Color.gray;
}
void Update () {
//Rectangle for box selection for future.
/* selectionBox = new Rect(Mathf.Min(originalPos.x, currentPos.x),
Mathf.Min(originalPos.y, currentPos.y),
Mathf.Abs(originalPos.x - currentPos.x),
Mathf.Abs(originalPos.y - currentPos.y)); */
}
/*void OnMouseEnter() {
GetComponent<Renderer>().material.color = Color.red;
}*/
void OnMouseOver() {
//Change color to blue when mouse is hovered over. This is working
GetComponent<Renderer>().material.color = Color.blue;
}
void OnMouseExit() {
//Change color back to gray when mouse moves away from unit. This is also working
GetComponent<Renderer>().material.color = Color.gray;
}
void OnMouseDown() {
//Create raycast when mouse is pressed down over collider
RaycastHit hitInfo = new RaycastHit();
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hitInfo)) {
//Add the hit collider into the unitsClicked list
unitsClicked.Add(hitInfo.collider);
//Go through the list and change color to red
foreach (Collider col in unitsClicked) {
col.GetComponent<Renderer>().material.color = Color.red;
Debug.Log(col);
}
}
}
void OnMouseDrag() {
}
}