Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Variable Becoming Null After Setting It

Discussion in 'Scripting' started by Corolla, May 8, 2022.

  1. Corolla

    Corolla

    Joined:
    Dec 7, 2021
    Posts:
    2
    Hi,

    I've created a class here called ShipController. ShipController is a component to a ship prefab that is instantiated by another script. After getting instantiated this other script then calls the Initialize() function. I put two debug statements in the code on lines 16 and 21. The log statement on line 16 correctly outputs the camera gameobject while the log statement on line 21 outputs null. I'm not sure why mainCam gets set in Initialize() but when FireWeapon() gets called mainCam is suddenly null. FireWeapon() never gets called before Initialize().

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class ShipController : MonoBehaviour
    6. {
    7.     public Camera mainCam;
    8.  
    9.     public List<GameObject> weapons;
    10.  
    11.     private int currentWeapon = 0;
    12.  
    13.     public void Initialize(Camera cam)
    14.     {
    15.         mainCam = cam;
    16.         Debug.Log(mainCam);
    17.     }
    18.  
    19.     public void FireWeapon()
    20.     {
    21.         Debug.Log(mainCam);
    22.         weapons[currentWeapon].GetComponent<WeaponBase>().Fire(transform.position, mainCam);
    23.     }
    24. }
    Please let me know what I'm doing wrong. Thanks!
     
  2. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    3,571
    Sound a lot like the same / similar issue as I explained over here. In short you probably reference the wrong object in one or both of the two cases. Add a context parameter to your Debug.Log statements to see which object(s) you're actually dealing with.
     
    Kurt-Dekker and Corolla like this.
  3. Corolla

    Corolla

    Joined:
    Dec 7, 2021
    Posts:
    2
    This was it! Thanks!