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;
}
}
CodePudding user response:
First you should check if there is a Collider on the Selectable. If not add one. Because you are asking for a Ray that hits a collider and if there's no Collider it will return always null
then this
Selectable selectable = hit.collider.gameObject.GetComponent<Selectable>();
if (selectable)
{
hit.collider.gameObject.GetComponent<Selectable>().Select();
}
is complete Nonsense why you get the Selectable in First Place and then the Selectable again? And you don't need a Collider on it to detect the Transform so you can remove the hit.collider to hit.gameObject or better is hit.transform (Because u don't need the whole GameObject)
hit.collider.gameObject.TryGetComponent(out Selectable selectable);
//hit.transform.TryGetComponent(out Selectable selectable)
if(selectable != null)
{
selectable.Select();
}
Then instead of
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Try
Ray ray = Camera.main.ViewportPointToRay(Input.mousePosition);
hope it helps you, if so, feel free to mark it as solved and correct Answer.