Raycashit Variable make empty/null/clear?

Hello Guys,

I need your help. First a little pice of my code (my question is at the bottom of the code):

...

    for (var i = 0; i < Input.touchCount; ++i) {

    var ray = Camera.main.ScreenPointToRay(Input.GetTouch(i).position);
    var hit : RaycastHit; // Thats the variable i want to clear at the end of the code

    if(Input.GetTouch(i).phase == TouchPhase.Began) {

        if (Physics.Raycast(ray, hit)) {

            if (hit.collider.gameObject == Button_Show_Help) {
                Button_Show_Help.renderer.material.color = Color.green;
            }

        }
    }

    else if(Input.GetTouch(i).phase == TouchPhase.Ended) {
        if (Physics.Raycast(ray, hit)) {

            if (hit.collider.gameObject == Button_Show_Help) {
                Button_Show_Help.renderer.material.color = Color.white;
            }
        }

The whole touch-code works like it should(above is just a litte pice of it) Thats not the problem. AFTER TouchPhase.Ended I want to clear the "hit.collider.gameObject" (which stores the touched object name). I already tryed this:

hit.collider.gameObject = null;

or

hit = null;

or

var hit_empty : RaycastHit;

hit = hit_empty;

But all this didnt work :( how can I clear this hit raycasthit variable

    }

1 Answer

1

You could just assign a new one over the top if you really wanted to:

hit = new RaycastHit();

The usual way to do it in c# would be to use default(RaycastHit), but that essentially does the same thing as the above, and doesn't work in js like you'd probably need

Just remember that RaycastHit is a struct - there isn't a "cleared" (i.e. null) state, it's always a valid instance. You also can't test if the instance is null, doing so will always return true. no matter what

If you're using it as a member variable, i'd suggest strongly against doing that, since usually the data only matters for a specific raycast

Looks like it's being declared as a local, first thing in the loop (but then I don't use Javascript much.) The question is missing a part. If he does another raycast, hit will be for that new one. If he doesn't do another raycast, why is he even checking hit?

Indeed, exactly what I was thinking

Thank you Mike for the explination! I found the solution for my problem after understanding the raycasthit struct :)