I understand from the documentation that FindWithTag should just return false if the object hasn't been created yet. But it throws a NullReferenceException instead.
Your NullReferenceException there isn't coming from your if/else statement, but from the assignment of newBullet. FindWithTag returns Null, not false, if it fails to find an object of that tag, and so you are attempting to get the transform of a null GameObject. The following code should do the checks properly.
var newBullet : Transform;
var newBulletObject : GameObject;
newBulletObject = GameObject.FindWithTag("bullet");
if (newBulletObject != null)
{
newBullet = newBulletObject.transform;
// Do something with bullet
}
else
{ // Do something knowing the bullet isn't on screen. }
The safer and less laborious way of doing these tests is with try/catch statements. These "try" to execute a piece of code, then "catch" any exceptions that fall through. I'm unsure if they are available in the JavaScript (UnityScript) implementation, however here is an example in C#.
Transform newBullet;
try
{
// Attempt to do everything in one line.
newBullet = GameObject.FindWithTag("bullet").transform;
// Do something with bullet
}
catch(Exception e)
{
// Something went wrong, so lets get information about it.
Debug.Log(e.ToString());
// Do something knowing the bullet isn't on screen.
}
This code will attempt to execute your assignment of newBullet, and if there are any exceptions thrown, it will fall into the catch statement and print the Exception information to the debug console. The Exception class I've used there is a catch all, and if you are expecting a more specific exception to be thrown, you can put another catch statement in there, replacing Exception with say NullReferenceException.
I see that there’s an accepted answer. But, there is a better answer for handling NullReferenceExcep[tion. If you can relate programming in Java language like me, you can prevent from sending a null error by using the try-catch block. Try it for yourself!
If you’re using in C#, check if you have using System; at the top of your script file. If not, add it. Now, you can use all sorts of Exception classes while try-catching a line of code.
If your’re using Javascript, use import System;
Here’s an example:
using System; // --> This exact line of code. That's it.
using UnityEngine;
public class Test : MonoBehaviour {
public GameObject player; // --> Example to check if there's a null content;
public void Update() {
// You may now catch null reference here.
try {
player.transform.Translate(0, 0, 2);
} catch(NullReferenceException e) {
}
}
}
Also remember, you can catch also other exceptions such as MissingReferenceException, MissingComponentException, IndexOutOfRangeException, or any other exception classes as long as you include using System in your script. That is all.