Touch different Gameobjects using camera array and raycast hit

I want to be able to touch a cube in the scene and have it print “cube” in the debug log and when I touch a sphere in the same scene I want it to print “sphere”. This is what i have…

function Update () {

 

    for (var touch : Touch in Input.touches){

	var ray = Camera.main.ScreenPointToRay(touch.position);
	var hit : RaycastHit;

	if (Physics.Raycast (ray, hit, 100)) {

		if(touch.phase == TouchPhase.Began || touch.phase == TouchPhase.Moved) {
		
		
			print("cube");
		
		
// this piece of code enables me to touch both cube and sphere but only display 
//"cube" in the debug log...

// I dont know how to separate the two
}
}
}
}

you’re not using a Debug.Log (at least not shown here)… You’re using “print”

you have a line that says

print(“cube”);
(not technically a Debug.Log)

this prints the word “cube” no matter what gets hit, the cube, the sphere, etc…

you could replace that line with this:

     print("Hit: " + hit.collider.name);

for a Debug Log, it would say:

  Debug.Log("Hit: " + hit.collider.name);

(to answer your other question, you can access the tag the same way, from the hit.collider):

...etc
if (Physics.Raycast (ray, hit, 100)) {
   if(touch.phase == TouchPhase.Began || touch.phase == TouchPhase.Moved) {
       if(hit.collider.tag == "someTag") {
           ...etc

Use the collider member of the RaycastHit variable you pass through to Raycast:


    var ray = Camera.main.ScreenPointToRay(touch.position);
    var hit : RaycastHit;
    
    if (Physics.Raycast (ray, hit, 100)) {
      if(touch.phase == TouchPhase.Began || touch.phase == TouchPhase.Moved) {
        print(hit.collider.name);
      }
    }

In this case it’s printing out the name of the object which has the collider component on, but you could check the tag or layer or anything else you like to work out what it is you’ve hit.

Why don’t you tag each of them and then in the ray cast section, check tag of the object.