Be the first to post for '23_MA_RPG'!

I took a bit of a different approach that does one RaycastAll.

void PerformRaycasts() {
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit[] raycastHits = Physics.RaycastAll(ray, maxRaycastDepth).OrderBy(h => h.distance).ToArray();
    foreach (RaycastHit hit in raycastHits) {
        if (CheckForEnemy(hit)) return; // Specify layer priorities here (order of checks matters)
        if (CheckForWalkable(hit)) return;
    }
    Cursor.SetCursor(unknownCursor, hotSpot, CursorMode.Auto);
}

This is a bit more efficient and deterministic. The Unity doc says that Physics.Raycast “Casts a ray, from point origin, in direction direction, of length maxDistance, against all colliders in the scene”. It will return a indeterminate collider from among all those that pass the layerMask.

Hi
I changed code to below code and my problem(null reference error for enemy Raycast) solved:

   bool RaycastForEnemy(Ray ray)
    {
        RaycastHit hitInfo;
        Physics.Raycast(ray, out hitInfo, maxRaycastDepth);
        if (hitInfo.collider != null)
        {
            var gameObjectHit = hitInfo.collider.gameObject;
            var enemyHit = gameObjectHit.GetComponent<Enemy>();
            if (enemyHit)
            {
                Cursor.SetCursor(enemyCursor, cursorHotSpot, CursorMode.Auto);
                onMouseOverEnemy(enemyHit);
                return true;
            }

        }
        return false;
    }

Is this is Right way?

Excuse me. This way is wrong.

Referencing this here as i have a few bugs one of which is fixed in the Q&A by me although the bug is created by me kinda.

  1. Some models not being detected as Enemy.
    A : I found the audio trigger i had on my models haad a sphere collider on it that was blocking the raycast to the Enemy script.
    A fix which i intend to fix by being implicite about which collider to look for not just any collider.

  2. 3D camera causing exceptions.
    A: Caused by the raycast being out of range ie too far in distance or skybox.
    This i solved in the Q&A code.

  3. NPC healer is now attackable.
    A: Caused by that they have an Enemy script. Solution remake the Healer a seperate class from Enemy but will factor it out later as not game breaking. Will psot the code if/when i do it :slight_smile:

Hope these help some people

Privacy & Terms