rayCastHit question

Hello everyone

So I’m trying to make a public class which does some calculations which i’ll be using a lot, i’ve called that class HandyMethods.cs.

What I wanted to do, is to make a method which checks if there’s a collision between A and B (with the Physics.Raycast() function), and if there is, return a rayCastHit variable which I could then use in many other scripts. But what I want, is to have an easy way to check if this function didn’t find a collision (the Physics.Raycast returned the “false” value).

If I define my function like this

public RayCastHit CheckForCollisions(){}

it would only be able to return a RayCastHit type variable, right?

So how do I make the function so it can return both a “true” boolean value and a RayCastHit type variable?

Two ways come to mind:

  • Return null if there was not hit, and check for that condition when calling the function.
  • Return a bool indicating whether or not there was a hit, and use an out parameter to store the RaycastHit, if any.

Unity’s own raycast functions opt for the latter option. You can see some examples here: http://unity3d.com/support/documentation/ScriptReference/Physics.Raycast.html

If you find the out keyword confusing, it may be a good idea to read up on searches like “csharp out keyword” or “pass by reference”.