Raycast All from mouse

i just want to be able to detect all colliders that the mouse is hovering over - this really shouldn’t be difficult but obviously im missing something.

right now my code looks like this

void Update() {
		RaycastHit[] hits;
		hits = Physics.RaycastAll(Input.mousePosition, Vector3.forward, 100.0F);
		int i = 0;
		while (i < hits.Length) {
			RaycastHit hit = hits*;*
  •  	Debug.Log (hit.collider.gameObject.name);*
    
  •  	i++;*
    
  •  }*
    
  • }*
    I know its bad form to put a debug log in update and its not going to stay there. At the moment that debug log doesnt even run - i assume because nothing gets added to hits. can some one point me in the right direction for this? please note that I don’t want to have to click, and i dont want to cast from a game object. i just want them all to be detected when i hover over it.

You can’t use the raw mouse position as the origin for your ray, it’s a 2D coordinate on the screen, not a 3D point in the world. You can however use the screen position to construct a ray from your camera using Camera.ScreenPointToRay(), like so:

hits = Physics.RaycastAll(Camera.main.ScreenPointToRay(Input.mousePosition), 100.0f);

Note that this is assuming you are currently viewing through the main camera :slight_smile:

figured it out. here you go for posterity sake

using UnityEngine;
using System.Collections;

public class RaycastTEST : MonoBehaviour {

	public Camera main;

	private Ray ray;


	void Update() {
		ray = main.ScreenPointToRay(Input.mousePosition);
		RaycastHit[] hits;
		hits = Physics.RaycastAll(ray);
		int i = 0;
		while (i < hits.Length) {
			RaycastHit hit = hits*;*
  •  	Debug.Log (hit.collider.gameObject.name);*
    
  •  	i++;*
    
  •  }*
    
  • }*
    }
    it was embarrassingly easy - i just had to buy the ray parameters earlier on and then use the ray in the raycast all.