Keep getting walkable although I am pointing on enemies

when I point on the red enemies I still get walkable. I made sure that all enemies have layer enemies and that their corresponding integers are correct in the utility class. Any ideas why

1 Like

Hi Habiba,

Can you pop a screenshot up of the Layer Priorites property from the Inspector, it’s a member variable of the CameraRaycaster.cs script component from memory, so select whichever GameObject in the Hierarchy has that attached.

problem1

It is attached to the camera arm object

Ok, so that looks good. Often people have the layers in a different order.

Can you copy/paste your CameraRaycaster.cs script too.


See also;

using UnityEngine;

public class CameraRaycaster : MonoBehaviour
{

    RaycastHit m_hit;
    Layer m_layerHit;
    [SerializeField] float distanceToBackground = 100f;
    Camera viewCamera;

    public Layer[] layerPriorities = {
        Layer.Enemy,
        Layer.Walkable
    };

   

   
    public RaycastHit hit
    {
        get { return m_hit; }
    }

    
    public Layer layerHit
    {
        get { return m_layerHit; }
    }

    void Start() // TODO Awake?
    {
        viewCamera = Camera.main;
    }

    void Update()
    {
        // Look for and return priority layer hit
        foreach (Layer layer in layerPriorities)
        {
           
            var hit = RaycastForLayer(layer);
            if (layer == Layer.Enemy)
            {
                Debug.Log("hit ? " + hit.HasValue);
            }
            if (hit.HasValue)
            {
               
                m_hit = hit.Value;
                m_layerHit = layer;
                return;
            }
        }

        // Otherwise return background hit
        m_hit.distance = distanceToBackground;
        m_layerHit = Layer.RaycastEndStop;
    }

    RaycastHit? RaycastForLayer(Layer layer)
    {
        int layerMask = 1 << (int)layer; // See Unity docs for mask formation
        Ray ray = viewCamera.ScreenPointToRay(Input.mousePosition);

        RaycastHit hit; // used as an out parameter
        bool hasHit = Physics.Raycast(ray, out hit, distanceToBackground, layerMask);
        if (hasHit)
        {
           // print("hit: " + layer);
            Debug.DrawLine(ray.origin, hit.point);
            return hit;
        }
        return null;
    }
}

The following part of the code always prints false even when I am pointing at an enemy

 if (layer == Layer.Enemy)
            {
                Debug.Log("hit ? " + hit.HasValue);
            }

okay I figured it out. I forgot to add a collider to ethan. But for some reason mesh colliders do not work, I had to add a box collider. Thanks :smile:

1 Like

I was literally about to sit down and take a look at this for you, hehe, glad you’ve managed to resolve it :slight_smile:

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms