RaycastHit doesn`t deselect?

Hey guys,

i`m attempting to write a simple script where a player object shoots out a ray and if a transform tagged “EnemyMain” crosses the ray, it gets detected and becomes a public _selectedTarget.

everything works fine, it detects enemies. but the problem is that it retains the selected target even though the ray is no longer intersecting with an enemy object.

the TargetSelection script is in void update. here`s the raycast part of the script:

public Transform _selectedTarget;
private Transform _transform;

void Update()
    {
        TargetSelection();
    }

private void TargetSelection()
    {
        RaycastHit raycastObject;
        Debug.DrawRay(_transform.position, _transform.forward * 10, Color.red);
        if (Physics.Raycast(_transform.position, _transform.forward, out raycastObject, 10))
        {
            if (raycastObject.collider.gameObject.tag == "EnemyMain")
            {
                Debug.DrawRay(_transform.position, _transform.forward * 10, Color.green);
                _selectedTarget = raycastObject.collider.transform;
            }
            else
            {
                Debug.DrawRay(_transform.position, _transform.forward * 10, Color.red);
                _selectedTarget = null;
            }
        }
    }

any help would be appreciated! thank you very much.

Lajos

EDIT: i would like to add that the debug line drawn does change color appropriately from red (nothing hitting ray) to green (enemy object intersecting) however the public transform _selectedTarget, remains the most recent object intersected.

You want to also set _selectedTarget to null in an else to your line 13 raycast if statement.

The reason: If you were seeing an enemy the transform would be non-null.

If you stop raycasting against anything, that variable just stays non-null.

If you prefer you can always set that variable to null at the start of your check… that’s another approach you might prefer.

2 Likes
private void TargetSelection()
    {
        RaycastHit raycastObject;
        Debug.DrawRay(_transform.position, _transform.forward * 10, Color.red);
        if (Physics.Raycast(_transform.position, _transform.forward, out raycastObject, 10))
        {
            if (raycastObject.collider.gameObject.tag == "EnemyMain")
            {
                Debug.DrawRay(_transform.position, _transform.forward * 10, Color.green);
                _selectedTarget = raycastObject.collider.transform;
            }
            else
            {
                Debug.DrawRay(_transform.position, _transform.forward * 10, Color.red);
                _selectedTarget = null;
            }
        }
        else //Need to set target to null if you don't hit anything with the raycast
        {
            _selectedTarget = null;
        }
    }
}
2 Likes

that`s it, problem solved!
thank you so much for the swift reply, i really needed a win today :)))

excellent, thanks a bunch!!! that did the trick!