Search Unity

Error with object referencing

Discussion in 'Scripting' started by magnus0, Nov 23, 2017.

  1. magnus0

    magnus0

    Joined:
    Nov 20, 2017
    Posts:
    4
    Unity is giving me the following error:
    NullReferenceException: Object reference not set to an instance of an object
    SupplyCrash.Update () (at Assets/SupplyDrop/Supply/SupplyCrash.cs:18)
    I know the issue is with the "smokeClone.transform.position = droppedSupply.transform.position;" part of the code (or I believe it is), but I have no idea how to correct it. Though the error is coming up, everything works as expected when I test the game. Here is the exact code I am using:


    Code (CSharp):
    1.     public GameObject crashSmoke;
    2.     public GameObject droppedSupply;
    3.     GameObject smokeClone;
    4.  
    5.     bool hasCollided = false;
    6.  
    7.     private void Update()
    8.     {
    9.         smokeClone.transform.position = droppedSupply.transform.position;
    10.     }
    11.  
    12.     private void OnCollisionEnter(Collision collision)
    13.     {
    14.         if (!hasCollided)
    15.         {
    16.             smokeClone = Instantiate(crashSmoke, transform.position, transform.rotation);
    17.             hasCollided = true;
    18.         }
    19.        
    20.     }
     
  2. Ian094

    Ian094

    Joined:
    Jun 20, 2013
    Posts:
    1,548
    "smokeClone" is assigned in the OnCollisionEnter() function but you are trying to reference it every frame in the Update() function.

    Consider checking whether it's null first:
    Code (CSharp):
    1. void Update()
    2. {
    3.     if(smokeClone != null)
    4.     {
    5.         smokeClone.transform.position = droppedSupply.transform.position;
    6.     }
    7. }