I have a method right now that will find the closest TreeInstance to something within a given distance range, and then return that TreeInstance. If there is not a single TreeInstance within the given distance range, I try to have the method return null.
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public static class TerrainExtensions {
/// <summary>
/// Finds the closest TreeInstance to the specified GameObject within "range"
/// </summary>
public static T FindClosestTreeInstanceTo<T>(this Terrain terrain, GameObject closestTo, float range)
{
TreeInstance closestTreeInstance = terrain.terrainData.treeInstances.OrderBy(treeInstance => Vector3.Distance(Vector3.Scale(treeInstance.position, terrain.terrainData.size) + terrain.transform.position, closestTo.transform.position)).First();
if (Vector3.Distance(Vector3.Scale(closestTreeInstance.position, terrain.terrainData.size) + terrain.transform.position, closestTo.transform.position) <= range)
{
return (T)Convert.ChangeType(closestTreeInstance, typeof(T));
}
else
{
return (T)Convert.ChangeType(null, typeof(T));
}
}
}
I believe it works as intended, however unity will throw the error "
“InvalidCastException: Null object can
not be converted to a value type.”
I don’t want anything returned if it’s not in range (null), but I don’t want Unity to throw these errors either.
IS there a better way to do this, or a way to suppress errors on that method?
Thanks!