null reference exception help!!!(solved)

this is my code and at the middle there is a code that is spouse to make my weapon turn and aim the direction of my mouse but it does not work. please help quick

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

public class weapon : MonoBehaviour
{
    public GameObject projectile;
    public Transform shotposition;
    private float Timebtwshots;
    public float starttime;
    public float offset;

   

    void Start()
    {
       
    }

    // Update is called once per frame
    void Update()
    { 
//makes my weapon turn but it keep  says that null reference exception in the below line 
        Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
        float rotZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
        transform.rotation = Quaternion.Euler(0f, 0f, rotZ + offset);
        if (Timebtwshots <= 0)
        {
            if (Input.GetMouseButtonDown(0))
            {
                Instantiate(projectile, shotposition.position, transform.rotation);
                Timebtwshots = starttime;
               
            }
        }else
        {
            Timebtwshots -= Time.deltaTime;
        }
    }
}

Seems suspicious that the nullref is in line 24 above. Input is static, transform is a provided read-only property of Monobehavior, so the only thing remaining is Camera.main, which is a helper to get the first camera it finds in the scene that is tagged “Main Camera”. Do you have a Main Camera in your scene at the instant this script runs?

oh I have forgot that i made a new camera thank you it was very helpful!!:smile:

1 Like