Why does this error occur?

Can someone help me? I programmed a script so that a weapon is always pointed at the player, but Unity throws this error: NullReferenceException: Object reference not set to an instance of an object
aim.Update () (at Assets/aim.cs:16)

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

public class aim : MonoBehaviour
{
    public Transform target;
    private Vector3 calculatettargetpos;
    private PLayerMovemondscript playercontroler;
    private float angle;

    // Update is called once per frame
    void Update()
    {
       
        calculatettargetpos = playercontroler.move + target.position;

        Vector3 targetDir = calculatettargetpos - transform.position;
        angle = Mathf.Atan2(targetDir.z, targetDir.x) * Mathf.Rad2Deg;

        transform.localRotation = Quaternion.Euler(0f, -angle -180 , 0f);
    }
}

A Null Reference means that some reference-type value is not set, or null in other words. Since it happens at line 16, either playercontroler or target are null. This means you probably forgot to set either of them (or both) through the inspector. Since playercontroler is private, you cant even set it through the inspector, and since it does not get set through this class, it is definitely null.

1 Like

Thanks