Dynamic Laser Fence Scripting Problem

Hi Everyone,

I have a player that starts out on an empty terrain. He can place turrets one by one that should shoot a laser at the closest turret once in place. This is to create a laser fence. The turrets used to shoot their lasers, but when I didn’t have the following script, they all shot at the second turret created. Thus I implemented this script, but now, the turrets won’t shoot anything at each other!

Here is my script for the finding of the closest turret:

//..........Finding Closest Turret
	var nearestDistanceSqr = Mathf.Infinity;
	var taggedGameObjects: GameObject[] = GameObject.FindGameObjectsWithTag("FenceLaserPoint1");
	var nearestTrt : Transform = null;
 
		// loop through each tagged object, remembering nearest one found
	for (var obj : GameObject in taggedGameObjects) {
 
		var objectPos = obj.transform.position;
		var distanceSqr = (objectPos - transform.position).sqrMagnitude;
 
		if (distanceSqr < nearestDistanceSqr) {
			nearestTrt = obj.transform;
			nearestDistanceSqr = distanceSqr;
		}
	}
	//................................

And here is my laser shooting code:

Laser=Instantiate(laserPrefab) as LineRenderer;
		if (Laser!=null)
		{
			Laser.SetPosition(0,thisLaserPoint.position);
			Laser.SetPosition(1,nearestTrt.transform.position);
			Destroy(Laser, laserEnergy);
		}

I know for sure that the laser shooting code is working well. It’s the scanning code to find the closest turret that isn’t working. Except, there are no errors so I cannot pinpoint any specific issues. I would greatly appreciate if you help me solve this problem.
Thank you,

Hyperion

In all honesty I think what you’re doing is just a little overly complicated. I’d just do something like this:

public static class Tools
{
    public static T FindNearest<T>(Transform reference) where T : MonoBehaviour
    {
    	return FindNearest<T>(reference.position);
    }

	public static T FindNearest<T>(Vector3 worldPosition) where T : MonoBehaviour
	{
        List<T> list = GameObject.FindObjectsOfType<T>().ToList();
            list.Sort(
            (x, y) =>
            (x.transform.position - reference).sqrMagnitude
            .CompareTo((y.transform.position - reference).sqrMagnitude));
        return list.First();
	}
}

To use it, you just pass a Type and a Transform, like so:

Turret nearestTurret = Tools.FindNearest<Turret>(transform.position);

Maybe that’s one of the advantages of using C#, because I’m not sure if that works in US or not.