Cant enter Target State

When i press TAB in play mode i get an null reference exception.

I can’t figure out what it is, been going through the code for an hour now and can’t find anything wrong, it was working before the “Improved Targeting Selection” lecture, though the camera was not locing onto the player; now nothing is happening and i get the following errors:


Targeter.cs

public bool SelectTarget()
    {
        if (targets.Count == 0) { return false; }

        Target closestTarget = null;
        float closestTargetDistance = Mathf.Infinity;

        foreach (Target target in targets)
        {
            Vector2 viewPos = mainCamera.WorldToViewportPoint(target.transform.position);

            if (viewPos.x < 0 || viewPos.x > 1 || viewPos.y < 0 || viewPos.y > 1)
            {
                continue;
            }

            Vector2 toCenter = viewPos - new Vector2(0.5f, 0.5f);
            if (toCenter.sqrMagnitude < closestTargetDistance)
            {
                closestTarget = target;
                closestTargetDistance = toCenter.sqrMagnitude;
            }
        }

        if (closestTarget == null) { return false; }

        CurrentTarget = closestTarget;

        cineTargetGroup.AddMember(CurrentTarget.transform, 1f, 2f);

        return true;
    }

PlayerFreeLookState.cs

void OnTarget()
    {
        if (!stateMachine.Targeter.SelectTarget()) { return; }
        stateMachine.SwitchState(new PlayerTargetingState(stateMachine));
    }

InputReader.cs

public void OnTarget(InputAction.CallbackContext context)
    {
        if (!context.performed) { return; }

        TargetEvent?.Invoke();
    }

Hey, @J0kk3 can you double-check you assigned the Target Group to the Targeter object?

I have, yes. Im going crazy. Dont know whats causing it…I even went through copying all code from the repo to make sure its correct, dont really know what could be causing it
Free Look Camera


State Driven Camera

Targeter

Targeting Camera

Targeting Group
targetingGroup

Ok, can you post the full code for Targeter.cs and PlayerFreeLookStete.cs and a Screenshot of your player prefab inspector view (to see how all things are hooked up)
Also, can you double-check if you applied all the prefab Overrides?

Heres how mines looks.

Targeter.cs

using System.Collections.Generic;
using Cinemachine;
using UnityEngine;

public class Targeter : MonoBehaviour
{
    [SerializeField] CinemachineTargetGroup cineTargetGroup;
    Camera mainCamera;
    List<Target> targets = new List<Target>();
    public Target CurrentTarget { get; private set; }

    void start()
    {
        mainCamera = Camera.main;
    }

    void OnTriggerEnter(Collider other)
    {
        if (!other.TryGetComponent<Target>(out Target target)) { return; }

        targets.Add(target);
        target.OnDestroyed += RemoveTarget;
    }

    void OnTriggerExit(Collider other)
    {
        if (!other.TryGetComponent<Target>(out Target target)) { return; }

        RemoveTarget(target);
    }

    public bool SelectTarget()
    {
        if (targets.Count == 0) { return false; }

        Target closestTarget = null;
        float closestTargetDistance = Mathf.Infinity;

        foreach (Target target in targets)
        {
            Vector2 viewPos = mainCamera.WorldToViewportPoint(target.transform.position);

            if (viewPos.x < 0 || viewPos.x > 1 || viewPos.y < 0 || viewPos.y > 1)
            {
                continue;
            }

            Vector2 toCenter = viewPos - new Vector2(0.5f, 0.5f);
            if (toCenter.sqrMagnitude < closestTargetDistance)
            {
                closestTarget = target;
                closestTargetDistance = toCenter.sqrMagnitude;
            }
        }

        if (closestTarget == null) { return false; }

        CurrentTarget = closestTarget;

        cineTargetGroup.AddMember(CurrentTarget.transform, 1f, 2f);

        return true;
    }

    public void Cancel()
    {
        if (CurrentTarget == null) { return; }
        cineTargetGroup.RemoveMember(CurrentTarget.transform);
        CurrentTarget = null;
    }
    void RemoveTarget(Target target)
    {
        if (CurrentTarget == target)
        {
            cineTargetGroup.RemoveMember(CurrentTarget.transform);
            CurrentTarget = null;
        }
        target.OnDestroyed -= RemoveTarget;
        targets.Remove(target);
    }
}

PlayerFreeLookState.cs

using UnityEngine;

public class PlayerFreeLookState : PlayerBaseState
{
    readonly int FreeLookSpeedHash = Animator.StringToHash("FreeLookSpeed");
    readonly int FreeLookBlendTreeHash = Animator.StringToHash("FreeLookBlendTree");

    const float AnimatorDampTime = 0.1f;

    public PlayerFreeLookState(PlayerStateMachine stateMachine) : base(stateMachine)
    {
    }

    public override void Enter()
    {
        stateMachine.InputReader.TargetEvent += OnTarget;
        stateMachine.Animator.Play(FreeLookBlendTreeHash);
    }

    public override void Tick(float deltaTime)
    {
        Vector3 movement = CalculateMovement();

        Move(movement * stateMachine.FreeLookMovementSpeed, deltaTime);
        if (stateMachine.InputReader.MovementValue == Vector2.zero)
        {
            stateMachine.Animator.SetFloat(FreeLookSpeedHash, 0, AnimatorDampTime, deltaTime);
            return;
        }
        stateMachine.Animator.SetFloat(FreeLookSpeedHash, 1, AnimatorDampTime, deltaTime);
        FaceMovementDirection(movement, deltaTime);
    }

    public override void Exit()
    {
        stateMachine.InputReader.TargetEvent -= OnTarget;
    }

    void OnTarget()
    {
        if (!stateMachine.Targeter.SelectTarget()) { return; }
        stateMachine.SwitchState(new PlayerTargetingState(stateMachine));
    }

    Vector3 CalculateMovement()
    {
        Vector3 forward = stateMachine.MainCameraTransform.forward;
        Vector3 right = stateMachine.MainCameraTransform.right;
        forward.y = 0f;
        right.y = 0f;
        forward.Normalize();
        right.Normalize();

        return forward * stateMachine.InputReader.MovementValue.y +
            right * stateMachine.InputReader.MovementValue.x;
    }
    void FaceMovementDirection(Vector3 movement, float deltaTime)
    {
        stateMachine.transform.rotation = Quaternion.Lerp(stateMachine.transform.rotation,
            Quaternion.LookRotation(movement),
            deltaTime * stateMachine.RotationDamping);
    }
}

Player prefab

Hmm, everything looks fine to me. Don’t know why you’re getting a null error when you want to select a target. Here’s my target prefab maybe that helps.

could i perhaps see your targeting camera prefab?
I just noticed my targeting camera changes if i add a target manually in play mode, but the main camera never switches to that camera.

NOTE: I updated unity to the newest LTS and updated cinemachine, no change

Here’s how my structure looks. I’ve all the relevant things









Thanks, nothing out of the ordinary, everythings the same here. im really confused

Did you try to create a new empty scene with just the player and an enemy? Or did you add/changed anything to your scene?

Tried it now, got the same error in a blank scene with just the player, 3D plane & a target

  1. Ok, select the new test scene you made and right-click on it > Select Dependencies
  2. Once you have that list, right-click again and create a new unity package.
  3. Upload that package on Dropbox/Google Drive/ One Drive / etc and post the link here so I can download it and take a look.


https://drive.google.com/file/d/1qou9mComG73kSUb0ZozSGSaLYGPj83bf/view?usp=sharing

So here is the error: You typed start with a lowercase “s” instead of “S”> that in turn made your main camera null > which in turn gave this error at line 41 :eyes:


My recommendation - get the free trial of Rider Rider: The Cross-Platform .NET IDE from JetBrains
It’s a superior coding IDE over the free VS Code / Studio.
I was able to spot the error because of its "fix naming " function which also fixed the “Start” naming issue.
you can see it in action here
naming bug - YouTube

Oh Oden allmighty. It’s always something simple isn’t it? Its not even marked wrong for me.
Thanks for all your time and patience
That fixed it

In case you didn’t know how the software development process works :))
This is what convinced me to switch to Rider - The advice that MADE ME a BETTER unity3d / c# programmer - YouTube
It’s my second year with it, and I never regretted the purchase.

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

Privacy & Terms