How to check if a GameObject exists?

Basically, I have a targetting AI, and I want them to do ‘other stuff’ if they have no target. BUT if (target) {etc; } is always true.

So. How to I go about checking if the object exists?

Probably something simple that I’m missing.

if (target != null)

?

the target is never nullified. :expressionless:

@MarkusDavey it sounds like the target is ever present in your scene, you could try doing a distance check between this entity and the target. If the target happens to be out of the range you’ve set, have it enter into an idle or similar state. I’ve attached a little snippet below to show what I am getting at.

// Check if the target is in hunting range
if(Vector3.Distance(this.transform.position, this._target.position) > this._huntRange)
{
	// Write to log of target being out of range
	Debug.Log("Target is no longer in hunting range, switching to idle state.");
				
	// Set the current state
	this._currentState = State.Idle;
}

Unity - Scripting API: GameObject.FindGameObjectsWithTag I think that is what you where talking about.

No. I have that. It’s just the way my target system works is that it makes a list of targets, then finds the nearest one, then that is the ‘target’. And it calls that every frame, and it uses ‘findobjectswithtag()’

but tbh, I’ll just check if the target is within ‘engage range’ .

Aha! Problem.

“NullReferenceException: Object reference not set to an instance of an object
EnemyAI.movetoTarget () (at Assets/_Scripts/AI/Enemy/EnemyAI.cs:273)
EnemyAI.locomotionManager () (at Assets/_Scripts/AI/Enemy/EnemyAI.cs:229)
EnemyAI.Update () (at Assets/_Scripts/AI/Enemy/EnemyAI.cs:72)”

on this line

if (target != null || Mhelper.getDistance(target.transform.position, transform.position) < AGGRORANGE)

Your logical statement is not very logical.

The compiler executes your test from left to right, so first… it goes

if (target != null)… suppose the target is NULL, well, it still needs to check the right half… right? Because the right half COULD be true and hence the whole logic statement would be true.

So then it starts to check the right half, and tries to access target.transform. But whoops, target is null. ERROR. DOES NOT COMPUTE.

What you’re looking for is

if (target != null … )

Hmm, Okay. I should stop programming at 5am :expressionless: lol.

Pfft, thats prime programming time!

Yeah i agree, 5am is when you get past tired and clarity sets in. Best time to be coding.