Lesson 86. ScreenToWorldPoint Target - Null Reference Exception

I’m getting an NullReferenceException: Object reference not set to an instance of an object
PlayerWeapon.MoveTargetPoint () (at Assets/Scripts/PlayerWeapon.cs:47)
PlayerWeapon.Update () (at Assets/Scripts/PlayerWeapon.cs:20) error on lesson 86.

I’ve tried both setting a Serialized Field and using GameObject.FindGameObjectWithTag for targetPoint but both ways are creating the same error. Here is my code:

using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerWeapon : MonoBehaviour
{
    [SerializeField] GameObject[] lasers;
    [SerializeField] RectTransform crosshair;
    [SerializeField] Transform targetPoint;
    [SerializeField] float targetDistance = 100f;
    bool isFiring = false;

    void Start()
    {
        Cursor.visible = false;
    }
    void Update()
    {
        ProcessFiring();
        MoveCrosshair();
        MoveTargetPoint();
    }

    public void OnFire(InputValue value)
    {
        isFiring = value.isPressed;

    }

    void ProcessFiring()
    {
        foreach (GameObject laser in lasers)
        {
            var emissionModule = laser.GetComponent<ParticleSystem>().emission;
            emissionModule.enabled = isFiring;
        }
            
    }

    void MoveCrosshair()
    {
        crosshair.position = Input.mousePosition;
    }

    void MoveTargetPoint()
    {
        Vector3 targetPointPosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, targetDistance);
        targetPoint.position = Camera.main.ScreenToWorldPoint(targetPointPosition);
    }
}

It’s probably not the targetPoint but the camera. Check your camera and make sure it has the MainCamera tag

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

Privacy & Terms