Search Unity

[SOLVED] Why does property return null? What am I doing wrong?

Discussion in 'Scripting' started by NoctisShadowzel, Jul 17, 2019.

  1. NoctisShadowzel

    NoctisShadowzel

    Joined:
    Dec 27, 2018
    Posts:
    57
    I'm doing a Free Fall level (infinitely falling), instead of implementing Custom Physics for this purpose, I decided to make Background move down while platforms move up to don't mess with character movement.
    Here is my problematic part of Platform Spawner script:
    Code (CSharp):
    1.  
    2.     (...)
    3.     IEnumerator SpawnPlatform()
    4.     {
    5.         GameObject newPlatform = null;
    6.         Vector3 lastPos = Vector3.zero,
    7.             newPos = Vector3.zero;
    8.  
    9.         bool isThisFirstLoop = true;
    10.  
    11.         while(true)
    12.         {
    13.             yield return null;
    14.  
    15.             Debug.Log("> " + this.gameObject.name + " () Platform Count: " + spawnedPlatformCount);
    16.            
    17.             if (CheckIfPlatformLimitReached() == true)
    18.                 continue;
    19.  
    20.             newPos = CalculateNewPosition();
    21.             if (!isThisFirstLoop && CheckIfNewPositionInDeadZone(lastPos, newPos) == true)
    22.                 continue;
    23.  
    24.             newPlatform = InstantiateNewPlatform(newPos);
    25.             if (newPlatform == null)
    26.                 continue;
    27.  
    28.             lastPos = newPos;
    29.  
    30.             if(isThisFirstLoop)
    31.                 isThisFirstLoop = false;
    32.             yield return new WaitForSecondsRealtime(spawnInterval);
    33.         }
    34.     }
    35.     (...)
    36.     GameObject InstantiateNewPlatform(Vector3 newPos)
    37.     {
    38.         if (backgroundSpawner.SelectedBackground == null)
    39.             return null;
    40.  
    41.         GameObject selectedPlatform = backgroundSpawner.SelectedBackground.name.Contains("bg_0") ?
    42.                             platform[1] : platform[0];
    43.  
    44.         return Instantiate(selectedPlatform, newPos, Quaternion.identity, platformListRootObject.transform);
    45.     }
    46. }
    And related Background Spawner script:
    Code (CSharp):
    1.  
    2. public GameObject SelectedBackground { get; private set; }
    3.  
    4.     public GameObject InstantiateNewBackground(Transform bgSpawn)
    5.     {
    6.         SelectedBackground = bg[Random.Range(0, bg.Length)];
    7.  
    8.         return Instantiate(SelectedBackground, bgSpawn.position, Quaternion.identity, bgList);
    9.     }
    I tried to debug code and noticed "SelectedBackground" property is null in "Platform Spawner" script. I don't know what is going wrong. Any ideas?

    TY for taking time ^.^ !
     
  2. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    1,258
    Well, SelectedBackground is an auto-implemented property with a reference type, so it will be null if you haven't set it to anything yet or if the last thing you set it to was null.

    It looks like you're trying to initialize it in InstantiateNewBackground(), but I guess either that function didn't get called before you needed it, or else you set it to an element from your "bg" array that was, itself, null.
     
  3. NoctisShadowzel

    NoctisShadowzel

    Joined:
    Dec 27, 2018
    Posts:
    57
    I debugged code ~10 times, by setting Breakpoints to that two Instantiate... methods. This is what happens each time;
    First; InstantiateNewBackground() get called.
    Second; InstantiateNewPlatform() get called, and surprisingly it spawns one Platform.
    After that, SelectedBackground property always returns null in "PlatformSpawner", but not in its own script ("BackgroundSpawner").

    - No, "bg" array isn't null, BackgroundSpawner keeps spawning new Backgrounds as it should do.
    - After spawning ONE platform ("InstantiateNewPlatform()"), function doesn't get called again.

    Isn't this weird? Maybe customizing "Script Execution Order" , will change outcome. Any other ideas?
     
  4. NoctisShadowzel

    NoctisShadowzel

    Joined:
    Dec 27, 2018
    Posts:
    57
    After changing the "Script Execution Order" according to; First execute "BackgroundSpawner" then execute "PlatformSpawner". Set Breakpoints on same functions ("Instantiate... methods"), ran 6 times.
    Three times debugger returned (0x1), this a is bad return value,
    Two times the "InstantiateNewBackground()" method never got called, even weirder - Backgrounds were keep spawning one after one...
    And in the last try Unity crashed, I got "Send a bug report" window.

    If there is someone from Unity, I can share my project via Drive, if this is eligable. Can you take a look at my project and tell me what am I doing wrong?:confused:
     
  5. bgulanowski

    bgulanowski

    Joined:
    Feb 9, 2018
    Posts:
    13
    Antistone suggested making sure that the array doesn't _contain_ null entries. But if the background spawner is working, that may or may not be the problem. Things to check:
    - is there only one background spawner?
    - or, does the background spawner get deleted and recreated?
    - do any other methods set SelectedBackground?

    A possible workaround is to expose a simpler method on BackgroundSpawner, like "bool Background0Selected()". You can either derive that
    Code (CSharp):
    1.  
    2. public bool BackgroundSelected => SelectedBackground.name.Contains("bg_0");
    3.  
    or
    Code (CSharp):
    1.  
    2. public bool BackgroundSelected { get; private set; }
    3.  
    and update it in "InstantiateNewBackground()".

    You can debug a property being null by breaking in the setter. That would mean rewriting the property to use an explicit private field, instead of an implicit field:
    Code (CSharp):
    1.  
    2. private GameObject _selectedBackground;
    3. public GameObject SelectedBackground {
    4.   get => _selectedBackground;
    5.   set {
    6.     _selectedBackground = value;
    7.     if (_selectedBackground == null) {
    8.       Debug.Log("SelectedBackground was cleared."); // add a breakpoint here
    9.     }
    10.   }
    11. }
    12.  
    Everything that happens in code happens for a reason. It's just a question of tracing the cause back to its source.
     
  6. NoctisShadowzel

    NoctisShadowzel

    Joined:
    Dec 27, 2018
    Posts:
    57
    @bgulanowski TY for the response. I still couldn't solve problem;

    Firstly, I used explicit private field you suggested; also deleted the null check from PlatformSpawner. I didn't get a message from Debug.Log that I wrote in BackgroundSpawner 's SelectedBackground properties setter, also Debugger was showing that SelectedBackground property is either bg_0 or bg_1. When it comes to PlatformSpawner, it is null. It is still spawning just ONE platform at the start of the game then stops.
    - Also there is no second BackgroundSpawner, never gets destroyed/recreated.
    - And, no, SelectedBackground isn't being set from any other script than BackgroundSpawner, also not being get from any other script than PlatformSpawner.

    Secondly, I used two bool fields, here is updated "BackgroundSpawer" and "PlatformSpawner". (I'm posting full scripts for both of them, there will be something that I missed.)

    PlatformSpawner:

    Code (CSharp):
    1. using System.Collections;
    2. using UnityEngine;
    3.  
    4. public class PlatformSpawner : MonoBehaviour
    5. {
    6.     [SerializeField] GameObject[] platform = new GameObject[2];
    7.     [SerializeField] EndlessPitBackgroundSpawner backgroundSpawner = null;
    8.     [SerializeField] Transform platformListRootObject = null;
    9.     [SerializeField] Transform spawnAreaL = null, spawnAreaR = null;
    10.     [SerializeField] float spawnInterval = 1f, spawnDeadZone = 0.1f;
    11.     [SerializeField] int spawnedPlatformLimit = 10;
    12.     int spawnedPlatformCount = 0;
    13.  
    14.     void Start()
    15.     {
    16.         StartCoroutine(SpawnPlatform());
    17.     }
    18.  
    19.     IEnumerator SpawnPlatform()
    20.     {
    21.         GameObject newPlatform = null;
    22.         Vector3 lastPos = Vector3.zero,
    23.             newPos = Vector3.zero;
    24.  
    25.         bool isThisFirstLoop = true;
    26.  
    27.         while(true)
    28.         {
    29.             yield return null;
    30.  
    31.             Debug.Log("> " + this.gameObject.name + " () Platform Count: " + spawnedPlatformCount);
    32.            
    33.             if (CheckIfPlatformLimitReached() == true)
    34.                 continue;
    35.  
    36.             newPos = CalculateNewPosition();
    37.             if (!isThisFirstLoop && CheckIfNewPositionInDeadZone(lastPos, newPos) == true)
    38.                 continue;
    39.  
    40.             newPlatform = InstantiateNewPlatform(newPos);
    41.             if (newPlatform == null)
    42.                 continue;
    43.  
    44.             lastPos = newPos;
    45.  
    46.             if(isThisFirstLoop)
    47.                 isThisFirstLoop = false;
    48.             yield return new WaitForSecondsRealtime(spawnInterval);
    49.         }
    50.     }
    51.  
    52.     bool CheckIfPlatformLimitReached()
    53.     {
    54.         spawnedPlatformCount = platformListRootObject.childCount;
    55.         return (spawnedPlatformCount >= spawnedPlatformLimit) ? true : false;
    56.     }
    57.  
    58.     Vector3 CalculateNewPosition()
    59.     {
    60.         return new Vector3(Random.Range(spawnAreaL.position.x, spawnAreaR.position.x),
    61.                         spawnAreaL.position.y);
    62.     }
    63.  
    64.     bool CheckIfNewPositionInDeadZone(Vector3 lastPos, Vector3 newPos)
    65.     {
    66.         Vector3 deltaVector = newPos - lastPos;
    67.  
    68.         bool isNewXInDeadZone = (Mathf.Abs(deltaVector.x) <= spawnDeadZone) ? true : false;
    69.         bool isNewYInDeadZone = (Mathf.Abs(deltaVector.y) <= spawnDeadZone) ? true : false;
    70.  
    71.         return (!isNewXInDeadZone && !isNewYInDeadZone) ? false : true;
    72.     }
    73.  
    74.     GameObject InstantiateNewPlatform(Vector3 newPos)
    75.     {
    76.         GameObject selectedPlatform = null;
    77.  
    78.         if (backgroundSpawner.BackgroundZeroSelected)
    79.             selectedPlatform = platform[1];
    80.         else if (backgroundSpawner.BackgroundOneSelected)
    81.             selectedPlatform = platform[0];
    82.  
    83.         return Instantiate(selectedPlatform, newPos, Quaternion.identity, platformListRootObject.transform);
    84.     }
    85. }

    BackgroundSpawner:

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class EndlessPitBackgroundSpawner : MonoBehaviour
    4. {
    5.     [SerializeField] Transform bgList = null;
    6.     [SerializeField] GameObject[] bg = new GameObject[2];
    7.  
    8.     private GameObject selectedBackground = null;
    9.     public GameObject SelectedBackground
    10.     {
    11.         get => selectedBackground;
    12.         private set
    13.         {
    14.             selectedBackground = value;
    15.             if (selectedBackground == null)
    16.                 Debug.Log("> selectedBackground is NULL.");
    17.         }
    18.     }
    19.  
    20.     public bool BackgroundZeroSelected { get; private set; }
    21.     public bool BackgroundOneSelected { get; private set; }
    22.  
    23.     public GameObject InstantiateNewBackground(Transform bgSpawn)
    24.     {
    25.         int index = Random.Range(0, bg.Length);
    26.  
    27.         BackgroundZeroSelected = (index == 0) ? true : false;
    28.         BackgroundOneSelected = !BackgroundZeroSelected;
    29.  
    30.         SelectedBackground = bg[index];
    31.  
    32.         return Instantiate(SelectedBackground, bgSpawn.position, Quaternion.identity, bgList);
    33.     }
    34. }
    This method doesn't directly using SelectedBackground property, but result is same. Also I don't know if it is important but, InstantiateNewBackground(...) method is being called by current background. When it reaches a point while moving down, it calls this method by giving bgSpawn argument that is child of background that calls this method. This way Backgrounds keep spawning one after one.

    While waiting for a response I'm going to reverse the script to change referencing mechanism. Maybe adjusting which platform is going to be next from BackgroundSpawner script will make a difference.

     
  7. NoctisShadowzel

    NoctisShadowzel

    Joined:
    Dec 27, 2018
    Posts:
    57
    Finally, I solved the problem. Also, I noticed there was actually two problems; and that customizing Script Execution Order, doesn't work as I thought.

    First, to solve NULLReferenceException, I used a bool check for if platformIsReadyToSpawn, because it became clear that until my Entrance Background passes certain point it doesn't call method for Instantiating Next Background. Also, because it is unclear if reference between BgSpawner and PltSpawner is working right, I added a method to call from BgSpawner that changes next platform to spawn. It still needs some tweak, though...

    Second; after I implemented new mechanics for Free Falling Level, I forgot that I call all platforms from a point that is below Camera and Player, and all platforms where instantiating in same Y position...

    Lastly, I'm sharing final scripts, in case any one will find them useful...

    BackgroundSpawner:

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class EndlessPitBackgroundSpawner : MonoBehaviour
    4. {
    5.     [SerializeField] Transform bgList = null;
    6.     [SerializeField] GameObject[] bg = new GameObject[2];
    7.  
    8.     private GameObject selectedBackground = null;
    9.     public GameObject SelectedBackground
    10.     {
    11.         get => selectedBackground;
    12.         private set
    13.         {
    14.             selectedBackground = value;
    15.             if (selectedBackground == null)
    16.                 Debug.Log("> selectedBackground is NULL.");
    17.         }
    18.     }
    19.  
    20.     [SerializeField] PlatformSpawner platformSpawner = null;
    21.  
    22.     public GameObject InstantiateNewBackground(Transform bgSpawn)
    23.     {
    24.         int index = Random.Range(0, bg.Length);
    25.  
    26.         platformSpawner.ChangeNextPlatform((index == 0) ? 1 : 0);
    27.         platformSpawner.IsPlatformReadyToSpawn = true;
    28.  
    29.         SelectedBackground = bg[index];
    30.  
    31.         return Instantiate(SelectedBackground, bgSpawn.position, Quaternion.identity, bgList);
    32.     }
    33. }

    PlatformSpawner:

    Code (CSharp):
    1. using System.Collections;
    2. using UnityEngine;
    3.  
    4. public class PlatformSpawner : MonoBehaviour
    5. {
    6.     [SerializeField] GameObject[] platform = new GameObject[2];
    7.     GameObject selectedPlatform = null;
    8.     [SerializeField] Transform platformListRootObject = null;
    9.     bool isPlatformReadyToSpawn = false;
    10.     public bool IsPlatformReadyToSpawn { get => isPlatformReadyToSpawn; set => isPlatformReadyToSpawn=value; }
    11.     [SerializeField] Transform spawnAreaL = null, spawnAreaR = null;
    12.     [SerializeField] float spawnInterval = 1f, spawnDeadZone = 0.1f;
    13.     [SerializeField] int spawnedPlatformLimit = 10;
    14.     int spawnedPlatformCount = 0;
    15.  
    16.     void Start()
    17.     {
    18.         StartCoroutine(SpawnPlatform());
    19.     }
    20.  
    21.     IEnumerator SpawnPlatform()
    22.     {
    23.         GameObject newPlatform = null;
    24.         Vector3 lastPos = Vector3.zero,
    25.             newPos = Vector3.zero;
    26.  
    27.         bool isThisFirstLoop = true;
    28.  
    29.         while(true)
    30.         {
    31.             yield return null;
    32.  
    33.             if (!IsPlatformReadyToSpawn)
    34.                 continue;
    35.  
    36.             Debug.Log("> " + this.gameObject.name + " () Platform Count: " + spawnedPlatformCount);
    37.            
    38.             if (CheckIfPlatformLimitReached() == true)
    39.                 continue;
    40.  
    41.             newPos = CalculateNewPosition();
    42.             if (!isThisFirstLoop && CheckIfNewPositionInDeadZone(lastPos, newPos) == true)
    43.                 continue;
    44.  
    45.             newPlatform = InstantiateNewPlatform(newPos);
    46.  
    47.             lastPos = newPos;
    48.  
    49.             if(isThisFirstLoop)
    50.                 isThisFirstLoop = false;
    51.             yield return new WaitForSecondsRealtime(spawnInterval);
    52.         }
    53.     }
    54.  
    55.     bool CheckIfPlatformLimitReached()
    56.     {
    57.         spawnedPlatformCount = platformListRootObject.childCount;
    58.         return (spawnedPlatformCount >= spawnedPlatformLimit) ? true : false;
    59.     }
    60.  
    61.     Vector3 CalculateNewPosition()
    62.     {
    63.         return new Vector3(Random.Range(spawnAreaL.position.x, spawnAreaR.position.x),
    64.                         spawnAreaL.position.y);
    65.     }
    66.  
    67.     bool CheckIfNewPositionInDeadZone(Vector3 lastPos, Vector3 newPos)
    68.     {
    69.         Vector3 deltaVector = newPos - lastPos;
    70.         return (Mathf.Abs(deltaVector.x) <= spawnDeadZone) ? false : true;
    71.     }
    72.  
    73.     public void ChangeNextPlatform(int nextPlatformIndex)
    74.     {
    75.         if (selectedPlatform != platform[nextPlatformIndex])
    76.             selectedPlatform = platform[nextPlatformIndex];
    77.         if (selectedPlatform == null)
    78.             Debug.LogWarning("selectedPlatform is NULL. What is going on?");
    79.     }
    80.  
    81.     GameObject InstantiateNewPlatform(Vector3 newPos)
    82.     {
    83.         return Instantiate(selectedPlatform, newPos, Quaternion.identity, platformListRootObject.transform);
    84.     }
    85. }
     
  8. NoctisShadowzel

    NoctisShadowzel

    Joined:
    Dec 27, 2018
    Posts:
    57