NullReferenceExeption (Help)

So, I have 2 types of targets;

  1. Auto Target = “target”
  2. Focus Target = “focousedTarget”

The function “dealDamageToTarget()” is Invoked every 2 seconds. However, If the Auto Target “target”, is Null as a result of going out of range, I get a Null reference error. Despite the fact that my “focousedTarget” is never null in this example.

my “target” becomes null if it leaves my attack radius based on screen shot;

    void dealDamageToTarget()
    {
        Debug.Log("A");

        if (myTargetScriptRefrence.focousedTarget != null)
        {
            Debug.Log("B");

            myTargetScriptRefrence.focousedTarget.GetComponent<UnitStats>();
            targetUnitStats = myTargetScriptRefrence.target.GetComponent<UnitStats>();
            targetUnitStats.damageHealth(myOwnUnitStats.damageOutPut);

            myOwnUnitStats.tottalShotsCounter(1);
        }
        else              //** SUPER CONFUSING, without the Curly brackets, this next function always ran even if the function before was satisfied... i dont recal this happening before
        {                                                                                     //for Some reason this bracket was a must, the next function always ran even if the first If function was satisfied "weird"
            Debug.Log("C");

            if (myTargetScriptRefrence.target != null)
            {
                Debug.Log("D");
                myTargetScriptRefrence.target.gameObject.GetComponent<UnitStats>();            //target is a transform, so I get its gameObject and then get its unit Stats script
                targetUnitStats = myTargetScriptRefrence.target.gameObject.GetComponent<UnitStats>();
                targetUnitStats.damageHealth(myOwnUnitStats.damageOutPut);                     //This sends Damage to the Targets unit Stats page

                myOwnUnitStats.tottalShotsCounter(1);                                          //This Counts how many shots we have fired into our unit stats page  //Could Possibly Also Count How much times we have gotten shot, and also use this to rank up my units
            }
            else

                Debug.Log("E");
            return;

        }

         
    }

Which line in your snippet is throwing the error? The line numbers don’t match up.

Solved: Line

  1. Changed to
targetUnitStats = myTargetScriptRefrence.focousedTarget.GetComponent<UnitStats>();

I do have more question which is also commented in this script. after the else statement, why did that function continue assuming the first Logic(if statement) was satisfied?

@Madgvox

There is no concept of significant whitespace in C#. When there are no brackets, only the immediately following statement is executed. You need brackets so that the compiler knows that that entire block is inside the else statement, and not just the Debug.Log statement.

So you saying I should always add the brackets after else? I swear I have scripts 2000 Line long with over 30 else statements and I never encountered this before lol.

If you want to have more than one statement in the else block, yes. I don’t know where you got the idea that brackets are always optional, but they are not.

I have no idea, How I got this far, without knowing this! or maybe I did and I forgot, I started programming about 2 months ago, I swear everyday i forget everything I did 2 days ago, and it feels like someone else wrote those scripts. I swear i read my own scripts and I get intimidated by them.

I swear for everything I learn, it seems Like I forget just as much. Getting old I guess

@Madgvox , thx for all the info, appreciate it man.

But why would the next statement run if the first if Statement was satisfied?

You will need to be more specific for me to give you a specific answer.

It’s really as simple as that if the code is not inside the else block, it doesn’t matter if the if statement was run or not.

so its almost like the else statement is nullified?

Heres an example; and in this example it says my second “if” statement is unreachable. but in my original script, it was always activating until I added those brackets;

What you’ve done there is created an else if block. Formatted differently, this looks like:

if( a ) {
  // a is true
} else if ( b ) {
  // b is true
}

Hopefully you can see that the second if is actually just part of the else block. In the snippet you posted above, you had created an if … else if … else series of statements:

if (myTargetScriptRefrence.focousedTarget != null)
{
  // etc.
} else if (myTargetScriptRefrence.target != null)
{
  // etc.
} else {
  // etc.
}

But then you added a Debug.Log inbetween your else and your if:

if (myTargetScriptRefrence.focousedTarget != null)
{
  // etc.
} else

Debug.Log( "C" );

if (myTargetScriptRefrence.target != null)
{
  // etc.
} else {
  // etc.
}

Which effectively turned your code into:

if (myTargetScriptRefrence.focousedTarget != null)
{
  // etc.
} else {
    Debug.Log( "C" );
}

if (myTargetScriptRefrence.target != null)
{
  // etc.
} else {
  // etc.
}

Hopefully now you can see why the second if statement was still evaluated.

This is a good example of why it is vitally important to keep your code formatting clean and consistent. Another one that I caught while making this post was your lack of brackets on the last else on line 29:

            else

                Debug.Log("E");
            return;

This will be seen by the compiler as if the return statement is not part of the else:

            else {
                Debug.Log("E");
            }
            return;

I’m not sure whether you intended the return statement to be inside the else block or not, and that’s kind of the problem. If your code is ambiguous to read, it makes it more difficult to tell whether you’re making a mistake that is semantically correct but will cause subtle bugs (like for example, adding a Debug.Log statement in-between an else if by accident).

1 Like

Holy shit, your amazing, love you bro!!! you should make videos