- Home /
The question is answered, right answer was accepted
RaycastHit "variable" in C#
Hi there, I've been trying to use this code wich seems very simple:
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast (ray))
{
print(hit.point);
}
And I'm getthing this error message: Use of unassigned local variable `hit'
Could someone please explain what am I doing wrong?
Thanks in advance,
(I'm having so much trouble trying to figure out this documentation in JS to C#, I wish they already had a fully documentated C# reference!)
Answer by Daniel-Brauer · Jul 21, 2010 at 03:53 AM
You need to use one of the versions of Physics.Raycast() that takes a RaycastHit argument. In your case, it would be:
Physics.Raycast(ray, out hit)
This version of the Raycast function will assign a value to hit, so you can (for instance) print hit.point.
Hi $$anonymous$$ Brauer,
Thank you for your reply. You're right, but after talking to another friend, there was also another error wich should be the initialization of a RaycasHit object using "new"... So, the code now looks like this:
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit hit = new RaycastHit();
if (Physics.Raycast (ray, out hit))
{
print("true" + hit.point);
}
Thanks! I am trying to convert an old javascript based game into C# and ran into this problem.
Answer by Caps · Jul 21, 2010 at 06:17 PM
Thanks to the help of Daniel Brauer and another friend, the actual code should look like this:
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit hit = new RaycastHit(); //*
if (Physics.Raycast (ray, out hit)) //**
{
print("true" + hit.point);
}
*- The RaycastHit type object called "hit" should be initialized with "new"
**- THere should be an "out hit" passed as argument for the Physics.Raycast function so that hit would receive a value
Sorry $$anonymous$$ike, I didn't understand very well. I would appreciate you explain better since I'm still learning.
Thank you
You don't assign to a variable if you're going to use it as an out parameter - i.e. the out hit parameter in this case. The idea is that the function you pass it to initializes it fully
Follow this Question
Related Questions
Raycast Distance Help 1 Answer
Raycashit Variable make empty/null/clear? 1 Answer
Global Variable Error 1 Answer