Not getting any hit results back for CombatTarget

Hi all,

For some reason, I’m not getting any matches when checking for the CombatTarget in my hits array. The InteractWithCombat function is getting called fine, and I get 1 or 2 hits back from the initial RaycastAll method - but then when I do the foreach I don’t get any results back.

Any ideas?

namespace RPG.Control
{
    public class PlayerController : MonoBehaviour
    {
    /// OTHER BITS

    private void Update()
    {
        InteractWithCombat();
        InteractWithMovement();
    }

    private void InteractWithCombat()
    {
        var hits = Physics.RaycastAll(GetMouseRay());
        foreach (var hit in hits)
            {
                var target = hit.transform.GetComponent<CombatTarget>();
                if (target == null) continue;

                if (Input.GetMouseButtonDown(0)) _fighter.Attack(target);
            }
    }
    /// OTHER BITS
}
using UnityEngine;

namespace RPG.Combat
{
    public class CombatTarget : MonoBehaviour
    {
    }
}
using UnityEngine;

namespace RPG.Combat
{
    public class Fighter : MonoBehaviour
    {
        public void Attack(CombatTarget target)
        {
            print("I'm attacking...");
        }
    }
}

You’re not ‘hitting’ your combat target.

The enemy has a collider, but the collider is not on the same game object as the CombatTarget script. So, when you do GetComponent<CombatTarget>() it doesn’t find that script because it doesn’t exist on the object you hit.

You will need to either move the CombatTarget script to the same game object as the collider, or move the collider to the same game object as the script.

Alternatively, you could use GetComponentInParent, but that will keep walking up the tree until it hits the root, or it finds the component. That means it could move out of your enemy completely and start climbing up the scene hierarchy

For best results, the collider should be on the Enemy GameObject itself, as that’s where we’ll be putting all of the other components for the game.

Thank you both - sorted now :smiley:

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

Privacy & Terms