- Home /
Adding an empty raycast hit to a list
I need to have an empty raycast hit be assigned to a list so it can be used as data for a raycast but I get a NullReferenceException whenever I try it. Here's what I did:
hits.Add(new RaycastHit());
RaycastHit hit = hits[hits.Count-1];
Physics.Raycast(turretMuzzle.position, turretMuzzle.forward, out hit, effectiveRange);
How should I do this?
Answer by Eric5h5 · Dec 19, 2012 at 05:02 AM
A RaycastHit is a struct, so when you make the "hit" variable, it's a copy of "hits[hits.Count-1]", not a reference. So "hits[hits.Count-1]" remains as a new RaycastHit with no data.
I could always create re-assign "hits[hits.Count-1]" as hits so hits[hits.Count-1] has data but I'm still getting the NullReferenceException for this line:
hits.Add(new RaycastHit());
Well, that's a different thing then...you apparently haven't initialized the "hits" variable.
Your answer
Follow this Question
Related Questions
Raycast is finding all items/script is finding all items - inventory help 1 Answer
A node in a childnode? 1 Answer
RaycastHit always returns 0 1 Answer
C# raycast shooting script broken 1 Answer