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. Dismiss Notice

Instantiating an object issue

Discussion in 'Scripting' started by v_chs, Sep 30, 2020.

  1. v_chs

    v_chs

    Joined:
    Dec 11, 2019
    Posts:
    64
    I try to instantiate an object. I set it as a public variable and I drag it to the inspector. If I try to Instantiate without checking if it's null, I get the error that the object I try to instantiate is null.

    When I check if it's null, I cannot read the list that is filled, some lines above, but the Instantiation works.

    The first prints the count correctly.
    In the second print, inside the if block, the count is 0

    Code (CSharp):
    1.         print("??" + burningCellAdjacentsList.Count);
    2.         if (fireClone != null && burningCellAdjacentsList.Count > 0) {
    3.             print("??*" + burningCellAdjacentsList.Count);
    4.         }
    5.  
    Did anyone handle a similar situation?
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,144
    If the count is 0, the second if doesn't execute. With that in mind, it's more likely you have two copies of the script in your scene. One where the list has values, the other which doesn't.
     
    Joe-Censored, v_chs and PraetorBlue like this.
  3. v_chs

    v_chs

    Joined:
    Dec 11, 2019
    Posts:
    64
    I cannot understand why the check if not null blocks the array count value.
     
  4. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,722
    It doesn't. 0 is not greater than 0, so
    burningCellAdjacentsList.Count > 0
    is not true, and you won't get inside the if statement if 0 the array size is 0. Therefore, if you're getting two logs, it's because there are two of these scripts in your scene, like @Brathnann said.
     
    Joe-Censored and v_chs like this.
  5. v_chs

    v_chs

    Joined:
    Dec 11, 2019
    Posts:
    64
    I think there's a misunderstanding here -maybe I did not express it well. Line 1 prints 8. There's no other script in the scene, or object attached in the same script.
     
  6. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,722
    You're saying line 1 prints 8 and line 3 prints 0? There must be other code you're not sharing with us.
     
    Joe-Censored likes this.
  7. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,144
    Agree with @PraetorBlue. There seems to be something missing if this code you shared is in a single method on the script, it would execute in order. It wouldn't change values between those two print calls on it's own.
     
    Joe-Censored likes this.