[CLOSED]RaycastAll Help

I don’t understand RaycastAll, I know how to use Raycast, but I don’t understand how you loop through all the hit points, and then find the closest.

I need RaycastAll because I’m hitting myself, which is not supposed to happen.

Heres the code. Its just basically saying if I hit fire1 shoot a RaycastAll, but thats it…:frowning: I don’t understand, and please explain how it works, so I can understand it.

Code:
using UnityEngine;
using System.Collections;

public class Shoot : MonoBehaviour {

	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
		if(Input.GetButtonDown ("Fire1")){
			Ray ray = new Ray(Camera.main.transform.position, Camera.main.transform.forward);
			RaycastHit[] hits;

			if(Physics.Raycast(ray, out hits)){

			}
		}
	}
}

You aren’t actually calling RaycastAll here. See the API page here. The code provides an example of how to use the function and how to loop through the results.

int layerMask = LayerMask.NameToLayer("Player");

RaycastHit[] hits;
hits = Physics.RaycastAll(transform.position, transform.forward, 100.0F, layerMask);
    
for(int rayIndex = 0; rayIndex < hits.Length; rayIndex++)
{
// Do something
}

To stop the ray from hitting your character you could set up a layer mask, which the API explains here.

And to sort the hit results by distance, a quick Google search has some help.