Hi! I have a base class which all units inherits from which works fine. In this class I have a function to change the color of the gameObject when it is selected/deselected. However, the private variable which stores the original color only uses the color I define when declaring it. The variable does not update to the actual original color of the current gameObject. Here is my code:
using UnityEngine;
using System.Collections;
public class UnitBaseClass : MonoBehaviour {
private bool isSelected = false;
private Color originalColor = Color.cyan;
// Use this for initialization
void Start () {
// Set color to all possible child objects
MeshRenderer[] meshRenderer = this.GetComponentsInChildren<MeshRenderer>();
originalColor = meshRenderer[0].material.color;
Debug.Log("OriginalColor: " + originalColor);
foreach (MeshRenderer mesh in meshRenderer) {
mesh.material.color = originalColor;
}
}
// Update is called once per frame
void Update () {
}
void OnMouseDown() {
// Toggle selected flag
if (isSelected==false) {
isSelected = true;
Debug.Log(gameObject + " selected");
// Mark selection with color by looping through all the children objects within the hitbox
MeshRenderer[] meshRenderer = this.GetComponentsInChildren<MeshRenderer>();
foreach (MeshRenderer mesh in meshRenderer) {
mesh.material.color = Color.red;
}
}
else {
isSelected = false;
Debug.Log(gameObject + " deselected");
// Mark selection with (original) color
MeshRenderer[] meshRenderer = this.GetComponentsInChildren<MeshRenderer>();
foreach (MeshRenderer mesh in meshRenderer) {
mesh.material.color = originalColor;
}
Debug.Log("OriginalColor: " + originalColor);
}
}
}
Below is my debug log which shows that the color is set the first time it is run (the Start-function), but after the select/deselect the original color changes back to cyan (which I used when declaring it). Why is the color not saved in the private variable? Any help is appreciated!
OriginalColor: RGBA(1.000, 1.000, 1.000, 0.500)
ship_hull (UnityEngine.GameObject) selected
ship_hull (UnityEngine.GameObject) deselected
OriginalColor: RGBA(0.000, 1.000, 1.000, 1.000)