Getting an error when hitting the enemy

So after following this part of the tutorial I get a weird error when striking the enemy, instead of the animation triggering on hit the game pauses and I get this:

“NullReferenceException: Object reference not set to an instance of an object
RPG.Characters.Player.AttackTarget (UnityEngine.GameObject target) (at Assets/_Characters/Player/Player.cs:93)
RPG.Characters.Player.OnMouseClick (RaycastHit raycastHit, Int32 layerHit) (at Assets/_Characters/Player/Player.cs:83)
RPG.CameraUI.CameraRaycaster.Update () (at Assets/_CameraUI/CameraRaycaster.cs:51)”

The code being referenced looks like this in my project:

In Player:

    private void AttackTarget(GameObject target)
    {
        var enemyComponent = target.GetComponent<Enemy>();
        if (Time.time - lastHitTime > weaponInUse.GetMinTimeBetweenHits())
        {
            animator.SetTrigger("Attack"); // TODO make const
            enemyComponent.TakeDamage(damagePerHit);
            lastHitTime = Time.time;
        }
    }

and:

    void OnMouseClick(RaycastHit raycastHit, int layerHit)
    {
        if (layerHit == enemyLayer)
        {
            var enemy = raycastHit.collider.gameObject;
            if (IsTargetInRange(enemy))
            {
                AttackTarget(enemy);
            }
        }
    }

And in CameraRaycaster:

    void Update()
    {
        // Check if pointer is over an interactable UI element
        if (EventSystem.current.IsPointerOverGameObject())
        {
            NotifyObserversIfLayerChanged(5);
            return; // Stop looking for other objects
        }

        // Raycast to max depth, every frame as things can move under mouse
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit[] raycastHits = Physics.RaycastAll(ray, maxRaycastDepth);

        RaycastHit? priorityHit = FindTopPriorityHit(raycastHits);
        if (!priorityHit.HasValue) // if hit no priority object
        {
            NotifyObserversIfLayerChanged(0); // broadcast default layer
            return;
        }

        // Notify delegates of layer change
        var layerHit = priorityHit.Value.collider.gameObject.layer;
        NotifyObserversIfLayerChanged(layerHit);

        // Notify delegates of highest priority game object under mouse when clicked
        if (Input.GetMouseButton(0))
        {
            notifyMouseClickObservers(priorityHit.Value, layerHit);
        }
    }

I solved it!

My player script was wrong. changed it to:

    private void SetupRuntimeAnimator()
    {
        animator = GetComponent<Animator>();
        animator.runtimeAnimatorController = animatorOverrideController;
        animatorOverrideController["DEFAULT ATTACK"] = weaponInUse.GetAttackAnimClip(); // remove const
    }

And now its working!

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

Privacy & Terms