r/UnityHelp • • Apr 10 '21

How do i fix this NullReferenceException im having?

Im using raycast to create a shooting function in my game and when i click to fire a NullReferenceException comes up, Here is my following code:

 void Update()
     {
         if (Input.GetButton("Fire1")) 
         {
             Shoot();
         }
     }
 
     void Shoot() 
     {
 
         Ray ray = mainCam.ScreenPointToRay(new Vector3(0.5f,0.5f,0));
         RaycastHit hit;
         if (Physics.Raycast(ray, out hit, database.weapons[id].range)) 
         {
             if(hit.transform.tag == "Enemy")
             Debug.Log(hit.transform.name);
             CharacterStats enemyStats = hit.transform.GetComponent<CharacterStats>();  
             enemyStats.TakeDamage(database.weapons[id].damage);
             Debug.Log(database.weapons[id].damage);
             
         }
     }

Specifically on the line where it says " Ray ray = mainCam.ScreenPointToRay(new Vector3(0.5f,0.5f,0));" is where i get the error. mainCam just refers to a variable that is assigned the value of Camera.main. What causes this problem?

2 Upvotes

1 comment sorted by

1

u/globalmaster17 Apr 14 '21

Cam = GetComponent<Camera>()

cam.ViewportPointToRay(new Vector3

Try this