I am doing a map, there are many objects in the map, what i want to realize is when one finger touch on the screen,i want to know which object i touch,there may be a function can return the object name. i am thinking about the “raycast” function, however it doesn’t work. can anybody help me?
For other noobs like me, you need to add a collider e.g. a box collider to the object you want to touch. I feel like such a noob although I am only 3 weeks in to Unity lol
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit = new RaycastHit();
if(Input.GetMouseButton(0)) {
if(Physics.Raycast(ray, out hit)) {
print(hit.collider.name);
}
}
This is for C#
I have modified your code a bit. Try this:
Touch touch = Input.touches[0];
Ray touchRay = Camera.mainCamera..ScreenPointToRay(touch.position);
RaycastHit[] hits = Physics.RaycastAll(touchRay);
foreach( RaycastHit hit in hits ) {
print("touching object name="+hit.gameObject.name);
}
Minor changes. See if they work.
EDIT: Do you need all of the objects hit or just the first object? RaycastAll may not be doing what you want. You may want to consider (as was posted already) using:
Physics.Raycast(ray, out hit);
Instead