C# Finding Closest Instance LINQ Error

Hello Everyone,

I’ve got a player on an empty terrain that can create instances of one type of a turret. Each turret is supposed to find another turret closest to itself and then shoot a laser at it in order to create a laser fence. I’m really close to achieving this, except the final step keeps getting errors (shown at bottom).

My code for the turret:

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;
	void Start()
		thisLaserPoint= transform.FindChild("LaserPoint1");
	// Update is called once per frame
	void Update () 
		if (!thisAnimator.GetBool("NotUpright"))
			Laser=Instantiate(laserPrefab) as LineRenderer;
			if (Laser!=null)
				Destroy(Laser, laserEnergy);
	void Scan ()
		Transform nearestTurret = Tools.FindNearest<TurretFence>(transform.position);


My code for finding the closest instance by type:

using UnityEngine;
using System.Collections.Generic;

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<T>().ToList();
		(x, y) =>
		(x.transform.position - reference).sqrMagnitude
		.CompareTo((y.transform.position - reference).sqrMagnitude));
		return list.First();

The two errors I’m getting are:

Tools.cs(13,43): error CS1501: No overload for method FindObjectsOfType' takes 0’ arguments


Tools.cs(18,29): error CS1061: Type System.Collections.Generic.List' does not contain a definition for First’ and no extension method First' of type System.Collections.Generic.List’ could be found (are you missing a using directive or an assembly reference?)

I would really appreciate any help to solve these errors. There are no problems with the laser rendering, just the scanning process. And I have not misspelled anything.

Thank you,


error CS1501: No overload for method FindObjectsOfType takes 0 arguments

What version of Unity are you using? FindObjectsOfType has a generic overload at least in Unity 4.3.2f1 and I don’t understand why you’d get that error unless you were using a version that didn’t support that overload.

error CS1061: Type System.Collections.Generic.List does not contain a definition for First and no extension method First of type System.Collections.Generic.List could be found (are you missing a using directive or an assembly reference?)

Check out the docs for First as it states which namespace it resides under.

(As Womrwood pointed out in their comment you forgot to include the System.Linq namespace)