Search Unity

"Null reference"

Discussion in 'Scripting' started by zlong1, Oct 13, 2018.

  1. zlong1

    zlong1

    Joined:
    Sep 7, 2018
    Posts:
    4
    Hello, I'm trying to learn how to script and encountered a null reference error. I know what it indicates, but I cannot figure out what I'm missing. I made another one that works and used its code as a template, but in doing so I created the error. The script is attached to the object that I'm referencing, which as I understand is the object that is supposed to be referenced. Could anyone please offer suggestions as to things that I could look at or even spot an oversight in the code?

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class ShootPowerUp : MonoBehaviour
    4. {
    5.     public GameObject pickupEffect;
    6.     PlayerShooting playerShooting;
    7.     public int DamageBoost = 25;
    8.  
    9.     void OnTriggerEnter(Collider other)
    10.     {
    11.  
    12.         if (other.CompareTag("Player"))
    13.         {
    14.             ShootPowerPickup(other);
    15.         }
    16.     }
    17.  
    18.     void ShootPowerPickup(Collider player)
    19.     {
    20.         Instantiate(pickupEffect, transform.position, transform.rotation);
    21.  
    22.         PlayerShooting power = player.GetComponent<PlayerShooting>();
    23.         power.damagePerShot = power.damagePerShot + DamageBoost; // [B]Null reference[/B] [B]error for this line[/B]
    24.         // Debug.Log("ShootPowerPickup");
    25.  
    26.         Destroy(gameObject);
    27.     }
    28. }
    29.  
     
  2. What is the exact error message and what line referenced in it?
     
  3. BmxGrilled

    BmxGrilled

    Joined:
    Jan 27, 2014
    Posts:
    239
    that error is saying that the power variable which is your PlayerShooting script, is null. Something is going wrong on your player.GetComponent<PlayerShooting>(); line. Make sure the player object has the PlayerShooting script on it.
     
  4. SparrowGS

    SparrowGS

    Joined:
    Apr 6, 2017
    Posts:
    2,536
    Or pickupEffect is unassainged
     
  5. BmxGrilled

    BmxGrilled

    Joined:
    Jan 27, 2014
    Posts:
    239
    Nope it would only be the player object or the GetComponent call, as you're not referencing the pickupEffect object.
     
  6. SparrowGS

    SparrowGS

    Joined:
    Apr 6, 2017
    Posts:
    2,536
    Line 20?