- Home /
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?
I would suggest creating a custom Class that contains two properties. One an instance of a RayCastHit and the other a boolean. Your function would then return an instance of this class which you can then check.
Another solution, would be return "null" for the RayCastHit to represent the fact that no hit happened.
Thanks that explained it ^^
And yes @Fattie, it's a great name :D Everyone should have one of those
Answer by rutter · Jun 06, 2012 at 09:40 PM
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".
Your answer
Follow this Question
Related Questions
Ray from enemy to player is always a bit off (Image) 1 Answer
RaycastHit.distance 1 Answer
Hit distance Change light range 1 Answer
How to hit two objects with only one shot (raycast) 0 Answers
Need help with Third person shooter 0 Answers