- Home /
Difficulties Clearing/Updating A Variable
I'm creating a script for an RTS like unit selection system. I'm trying to make the script assign the value of a variable "Selected" to whatever the user clicks on, and turn the selected unit green. If the user clicks something else, the selected variable will be cleared, and the unit previously selected will no longer be green. Here's my code:
using UnityEngine;
using System.Collections;
public class Select : MonoBehaviour
{
public GameObject selected;
public Ray ray;
RaycastHit hit;
void OnMouseDown() {
selected = null;
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Physics.Raycast(ray, out hit);
if( Physics.Raycast( ray, out hit, 100000F) )
{
selected = hit.collider.gameObject;
Debug.Log (name);
}
selected.renderer.material.color = Color.green;
}
}
My issue is that the selected variable will only hold the value of whatever was clicked on first. The variable isn't cleared when I click off of a unit. Additionally, whenever I click on anything, regardless of whether or not it is set equal to the selected variable, it turns green. The Debug.Log (name); statement works just fine.
Your answer
Follow this Question
Related Questions
Can't update value of var in another class 1 Answer
Glitchy variable when updating through a function 2 Answers
Rotate Object with mouse in RTS style game 2 Answers
Raycast not visible 1 Answer