- Home /
Subtracting the position of transform from the position of Game Objects in a list.
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!
Answer by b1gry4n · Jul 17, 2021 at 02:21 PM
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[i].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);
Thanks! I still have to try out the script but reading your code gives me the hope that it most certainly will work! I appreciate it, mate!
@b1gry4n The script works, but I have a problem. I have a Transform
called as Target. So, how would I set the Target equal to the Closest Cover?
@b1gry4n I solved it. I just set the target equal to the transform of closest Cover. Like this:
Target = closestCover.transform;
Thanks for the help, mate. appreciate it.
Your answer
Follow this Question
Related Questions
Any way to change transform.position of an indefinite number of gameobjects on FixedUpdate? 2 Answers
How to add elements from a List of another class to another List (C#) 1 Answer
Clear Does not work to remove 1 Answer
Ordering a list of GameObjects 3 Answers
Runtime instantiation based on XML 1 Answer