RaycastHit unassigned...

I’m attempting to use RayCastHit (see below) within Physics.Raycast, but Unity keeps giving me the “unassigned local variable” on hit. I was under the impression that the RaycastHit Type would be defined when called if valid, or null otherwise. Is my syntax incorrect? Any ideas on what I’m missing?

        if (Input.GetButtonDown("Fire1"))
        {
            mouseButton1DownPoint = Input.mousePosition;
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition); 

            if (Physics.Raycast (ray, hit, raycastLength, terrainLayerMask) )
            {               
                print("Mouse Down Hit Terrain " + hit.point);
                mouseButton1DownTerrainHitPoint = hit.point;
                leftRectStart = hit.point;
                mouseLeftDrag = true;
            }
        }

It should be noted that I’m porting code from another person’s Jscript.

It seems your converting to C#, so:

C# enforces a definite assignment policy. This means, among other things, local variables must be assigned a value before they can be read.

The compiler thinks your trying to read from ‘hit’, that’s why it’s giving you the error. Use the parameter modifier ‘out’ before ‘hit’:

if (Physics.Raycast (ray, out hit, raycastLength, terrainLayerMask) )

So the compiler knows the variables ‘hit’ is going to be written-to not read- from.

1 Like

Ah- thank you!.. I’ve only been working in C# for about 6 months now. I hadn’t come across a need for that yet.

Much appreciated!