- Home /
how to fix a null reference exception when a findgameobjectwithtag does not exist
Hi there, i'm having a slight problem with part of my code for a game i'm developing.
The basic premise is that an object will intercept another object is within range, quick note is that i'm not using sphere colliders for this purpose as they interfere with lens flare effects.
I have a public variable set up as "Target : Gameobject" andd then
Target = findgameobjectwithtag ("Friendly")
If (Target.distance < RadarRange) { Intercept() }
If (!Target) { Patrol() }
However, when the object (Friendly) has been destroyed i get a null reference exception and the game slows down to a crawl with then enemy objects just flying off in a straight line and not patrolling. Is there anyway to fix this so that when the target variable is null that the enemy fighters go back to patrolling?
Forgive me for the spelling i'm on my mobile and at work, plus i've tried to remember the code as best i can since i don't have it to hand but i'm sur you can get the basic gist of wht i'm trying to do.
Many thanks
Answer by Dave-Carlile · Apr 12, 2013 at 01:06 PM
Seems like you're on the right track...
Target = FindGameObjectWithTag("Friendly");
if (Target == null)
Patrol();
else if (Target.distance < RadarRange)
Intercept();
else
Patrol();
In English, if there is no target then patrol, otherwise if there is a target within the radar distance then intercept, otherwise there is a target, but it's too far, patrol. This code can be simplified a bit...
Target = FindGameObjectWithTag("Friendly");
if (Target != null && Target.distance < RadarRange)
Intercept();
else
Patrol();
Same idea, but it does the target existence and distance check in a single line with "and".
I'll try it when i get home, but it looks and sounds correct
Just tried it, it still didn't work, here is the section of code with the refinements, the problem is in the Target variable reference : Target = GameObject.FindWithTag ("Friendly").transform;
function FixedUpdate ()
{
rigidbody.AddForce (transform.forward * (PatrolSpeed * Time.deltaTime));
Target = GameObject.FindWithTag ("Friendly").transform;
if (Target != null && Vector3.Distance (Target.position, transform.position) < RadarRange)
{
IsIntercepting = true;
IsPatrolling = false;
rigidbody.AddForce (transform.forward * (InterceptSpeed * Time.deltaTime));
Intercept();
//Debug.Log("Radar Contact, $$anonymous$$oving to Intercept - Red Fighter"
}
else
{
IsAttacking = false;
IsIntercepting = false;
Patrol();
}
It's the .transform
part of your code. The function call to FindWithTag
is returning null
, then you're trying to access the transform
property. You need to split that into two pieces. Get the game object itself. If that's null then patrol. If it's not null then you can safely get the transform
...
GameObject go = GameObject.FindWithTag("Friendly");
if (go == null)
Patrol();
else
{
Transform target = go.transform;
.... the rest of your intercept code...
}
Your answer
