Hello Everyone,
I’ve been working on this issue for a whole week now, and I can’t get a working solution. I have a turret that should shoot a laser at the closest other turret to create a laser fence. Except the turrets just refuse to find the closest turret! I’m getting frustrated.
Here’s my turret code:
using UnityEngine;
using System.Collections;
public class TurretFence : MonoBehaviour {
public LineRenderer laserPrefab;
private LineRenderer Laser;
private float laserEnergy= 0.01f;
private Animator thisAnimator;
private Transform thisLaserPoint;
private Transform nearestTurret;
void Start()
{
thisAnimator=GetComponent<Animator>();
thisLaserPoint= transform.FindChild("LaserPoint1");
}
// Update is called once per frame
void Update ()
{
nearestTurret = Tools.FindNearest<TurretFence>(transform.position).transform;
if (!thisAnimator.GetBool("NotUpright"))
{
Laser=Instantiate(laserPrefab) as LineRenderer;
if (Laser!=null)
{
Laser.SetPosition(0,thisLaserPoint.position);
Laser.SetPosition(1,nearestTurret.position);
Destroy(Laser, laserEnergy);
}
}
}
}
and my finding code:
using UnityEngine;
using System.Collections.Generic;
using System.Linq;
public class Tools {
public static T FindNearest<T>(Transform reference) where T : MonoBehaviour
{
return FindNearest<T>(reference.position);
}
public static T FindNearest<T>(Vector3 reference) where T : MonoBehaviour
{
List<T> list = (GameObject.FindObjectsOfType(typeof(T)) as T[]).ToList();
list.Sort(
(x, y) =>
(x.transform.position - reference).sqrMagnitude
.CompareTo((y.transform.position - reference).sqrMagnitude));
return list.FirstOrDefault();
}
}
All the turrets do is fire at themselves or fire into nothingness.
That red line at the turret is the laser.
I appreciate any suggestions.
-Hyperion