I need to “select” objects by clicking on them. I’m using Raycast to check if a collision is present at the x and y mouse coordinates. That’s working fine. But, I need to code the following: if user clicks on object called “Cube”, do this… if user clicks on object called “Triangle”, do that…
if (Physics.Raycast (ray, hit, 10000))
{
if (hit.collider == Cube) {
hit.collider.transform.rotate(0,0,5);
}
The above code doesn’t work because Unity doesn’t recognize “Cube” – the name of the object in the Hierarchy. How would I reference “Cube” from the hierarchy?
hit.collider will return the collider component that was hit by the raycast. The collider itself doesn’t really have a unique name that you can change, so you need to get the game object it’s connected to. Just like when you use hit.collider.transform to get the transform component that is on the same game object you hit, you can get the game object itself.
For example, if you called your game object “MyCube” in the heirerchy:
if (Physics.Raycast (ray, hit, 10000))
{
if (hit.collider.gameObject.name == "MyCube")
{
hit.collider.transform.rotate(0,0,5);
}
}
Brilliant cyb3rmaniak! Just what I was looking for. Kudos.