Need help with CS0128

private void Update()
    {
        // Emits a ray in the direction the player is facing
        Vector3 direction = Vector3.forward;
        Ray theRay = new Ray(transform.position, transform.TransformDirection(direction * range));

        // Draws the ray in the scene view
        Debug.DrawRay(transform.position, transform.TransformDirection(direction * range));

        if (Physics.Raycast(theRay, out RaycastHit hit, range))
        {
            if (hit.collider.tag == "Photo target")
            {
                print("Take a picture.");
            }
        }

        // When left mouse button is pressed the camera takes a picture
        if (Input.GetMouseButtonDown(0) && (Physics.Raycast(theRay, out RaycastHit hit, range)))
        {
            // If not viewing a picture a picture is taken
            if (!viewingPhoto)
            {
                StartCoroutine(CapturePhotoWithMoney());
            }
            // If viewing a picture the picture is removed from the screen
            else
            {
                RemovePhoto();
            }
        }

The CS0128 says “A local variable or function called ‘hit’ is already defined in this scope” and it referres to the hit on the if (Input.GetMouseButtonDown(0) && (Physics.Raycast(theRay, out RaycastHit hit, range))) line

Yes, you define hit twice as the error states. On line 10 initially then on line 19. In C# when you define the type and arg name it defines it for you there and then. This is a convenience thing but you cannot do it twice; you can’t define two things of the same name in the same scope.

Just put “RaycastHit hit;” on Line 9 then just pass in “out hit” on lines 10 and 19.

See: C# 7 - New Inline Out Variables - CodeProject

Forget error codes, don’t even post them on the forums. Just read the error description.

Thank you, it worked and i’ll try to remember to not post the error codes

1 Like

You can post them but they are not the important part unlike the description and the line numbers etc. You use code-tags which is great, a lot of devs don’t! :slight_smile:

1 Like

Just to add a bit of context to what MelvMay said: a lot of people only post the error codes. Which is also, for example, done in the title here. The error code is useless and holds “no” information. Also, noone memorizes them (for the same reason). The important parts are the description of the error, which also contains the line numbers. This tells us what and where (specifically for your code) the problem occurs, and is usually very accurate (unless there is a structural problem, which usually makes the compiler incapable of correctly interpreting the file).
This is also why using code tags is fantastic, since it adds line numbers. So posting the full error message and the relevant code using code tags gives anybody reading it all the information necessary to resolve the error. At least from a technical viewpoint.

2 Likes