as I stated above, I need help with my c# code which I'm using in unity to make a 3D game. When I click on an object it should change color and if there was previously another object selected, I need it to be deselected automatically. I already wrote a code which is supposed to at least help me select(change a material color) but it isn't working. I am checking if the left mouse button is pressed down and using raycast to check if there is something under a cursor. Also wrote a Selection class with 2 methods(Select/deselect) that are supposed to change color of an object. I'll be thankful if you can help me. Here's the code with mouse click:
public class ClickSelect : MonoBehaviour
{
private void Update()
{
Click();
}
public void Click()
{
if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
Selectable selectable = hit.collider.gameObject.GetComponent<Selectable>();
if (selectable)
{
hit.collider.gameObject.GetComponent<Selectable>().Select();
}
}
}
}
}
And this is code of a selection class:
public class Selectable : MonoBehaviour
{
public void Select()
{
GetComponent<Renderer>().material.color = Color.yellow;
}
public void Deselect()
{
GetComponent<Renderer>().material.color = Color.gray;
}
}