Closest target acquisition using Physics Overlap Sphere script not working

Hey guys, this is my first post so bear with me :slight_smile:

I’m trying to create a target acquisition script using a physics overlap sphere mechanic. I’m very new to coding so this is the best I could do atm. I tried to set the turret to turn towards the closest target within the overlap sphere. However I keep running into a lot of errors and I managed to narrow it down to this… but im fairly stumped! It tells me “Object reference not set to an instance of an object”, however I am sure I set the beginning instance to null “closest”.

Basically, my plan is to find all collisions within sphere, find the closest one’s position then have my turret face towards that target.

Any help would be really appreciated!

var damping = 6.0;
var smooth = true;
var attackRange = 50;

var test = true;
static var targetTag : String;

var targets = GameObject;

 
function Start()
{
//	InvokeRepeating ("FindClosestEnemyPlayer", 0, 1);
}
 
function Update()
{  
	if (test == true)
	{	
		var hit : RaycastHit;
		var ray : Ray;
		var fwd = transform.TransformDirection (Vector3.forward);
		if (Physics.Raycast (transform.position, fwd, hit, attackRange))
		{
			if(hit.collider.name == "Player")
			{
				print("target` hit!");
			}
		}	
		if (Physics.Raycast (transform.position, fwd, attackRange))
		{
		}
		Debug.DrawRay (transform.position, fwd * attackRange, Color.white);
	}

//Script for rotating towards acquired target
	if (test == true)
	{
		if (smooth)
		{
			var target : Transform = FindClosestTarget();
			// Look at and dampen the rotation
			var rotation = Quaternion.LookRotation(target.position - transform.position);
			transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping);
		}
	}
}


function FindClosestTarget() : Transform
{
	var closest : Transform = null;
	var origin : Vector3 = transform.position;
	var distance = Mathf.Infinity;
	var cols : Collider[] = Physics.OverlapSphere(origin, attackRange);
 
	for (var hit : Collider in cols)
	{
		var diff = (hit.position - origin);
		var curDistance = diff.sqrMagnitude;
		if (curDistance < distance)
		{
			distance = curDistance;
			closest = hit.transform;
		}
	}
	return closest;
}

I see one problem here. Your function findClosestTarget() returns null if Physics.OverlapSphere() does not find any colliders. But on line 43 you use target.position without checking if target is null. Line 8 is also weird. You set ‘targets’ to the class ‘GameObject’. I think you want:

var targets : GameObject;

I believe having #pragma strict at the top of the file would have found this issue at compile time. It is always a good idea to have ‘#pragma strict’ at the top of the file.