I want to make a crouch system in Unity, First, I have a script with the bool Coverable which is always true.
I want to make a list with all of the objects that have the script called as “Cover”. Then, in a certain method,
I would like to subtract the current position of transform from all of the objects in that list and travel to the
closest one. How can I do that? Also, I’m using Navmesh Agent and C#.
P.S Sorry for my bad english, grammar and explanation!
the easiest way i can think of is having a new cover manager script that you can access all cover objects from. So for example…
public class CoverManager : MonoBehaviour
{
public static CoverManager _this;
List<CoverObject> coverObjects = new List<CoverObject>();
private void Awake()
{
_this = this;
}
public static void AddCover(CoverObject coverObject)
{
_this.coverObjects.Add(coverObject);
}
public static CoverObject GetClosestCover(Vector3 from)
{
float dist = Mathf.Infinity;
int index = 0;
for(int i = 0; i < _this.coverObjects.Count; i++)
{
float d = Vector3.Distance(from, _this.coverObjects*.transform.position);*
if(d < dist)
{
index = i;
dist = d;
}
}
return _this.coverObjects[index];
}
}
then inside your cover object you need to add itself to the covermanagers list
public class CoverObject : MonoBehaviour
{
void Start()
{
CoverManager.AddCover(this);
}
}
and finally whenever you want to find the closest object from any script you simply call
CoverObject closestCover = CoverManager.GetClosestCover(this.transform.position);