Sending <Target> to Another Method: NULLREF

Hey folks,

So I’m having an issue where I’m trying to send the “CurrentTarget” from a CinemachineTargetGroup to another script that handles are the status bars. I’ve seemed to have hit a roadblock as no matter which way I try and send the data over, I keep getting a reference error even thought when I log out the variable, its correct.

Perhaps I’m missing something. Here is the code in question:

public Target CurrentTarget { get; private set; }

public BarsManager barsManager;
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 (!target.GetComponentInChildren<Renderer>().isVisible)
        {
            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);

    barsManager = GetComponent<BarsManager>();

    // IF not null then send the currenttarget to the HealthCheck method in BarsManager

    if (CurrentTarget != null)
    {
        barsManager.EnemyHealthCheck(CurrentTarget);
    }

    return true;
}

|----------------------------------|

Bars manager input script

public void EnemyHealthCheck(Target target)
{

    Debug.Log(target);
  
}

I am declaring BarsManager above the script so that is not the issue.

Post your error! It contains all the info you need to solve a null error. Also, if line 41 is null, then barsManager is null, which means nothing is assigned to the variable. But, no way to know because we don’t know what line the error is on. Otherwise…

  1. Find out what is null
  2. Find out why it’s null
  3. Fix it.

The three simple steps for all null errors.

2 Likes

Sorry I thought I did post the error. I ended up fixing it though. I made a new script on the PreFab and targeted the exact information I needed instead of trying to keep the scripts outside of the PreFabs.