Track only closest enemy transform
How can I achive that I'm only targeting the closest enemy? Even better would be to "loose" the target if the target comes to close to the player. Jumping on the next target in range, if there is any.
Here is my code:
public class PlayerInput : MonoBehaviour
{
public Transform target;
void lookForTarget()
{
if (GameObject.FindWithTag("Enemy") != null)
{
target = GameObject.FindWithTag("Enemy").transform;
target.Find("TargetGui").GetComponent<Renderer>().enabled = true;
}
}
}
Thanks
Answer by nathanlink169 · Sep 15, 2018 at 04:48 PM
Transform[] enemies = GetEnemies();
float closestDistance = float.MaxValue;
Transform closestEnemy = null;
for(int i = 0; i < enemies.Length; ++i)
{
float currentDistance = Vector3.Distance(m_player.position, enemies[i].position);
if(currentDistance < closestDistance)
{
closestDistance = currentDistance;
closestDistance = enemies[i];
}
}
In the end, whatever is in closestEnemy will be the one you're looking for.
I still don't get it, trying desperately to integrate this, but I have no idea how. Where should I put it? This dosn't work, too- :( I have the example code from unity, but it's dosn't get the closest, running the loop means no difference than not running it. In other words, the targets won't switch. Please show full code
This piece of code is used to find the closest enemy in an array of enemies. How you get the array is up to you, and when you trigger this piece of code is up to you.
I would recommend thinking about the piece of code, understanding how it works, and how it could be integrated into your code. Giving you a full piece of code that you can plug-and-play will do very little for your learning.
I know how the code works. I've been looking at this for days; https://docs.unity3d.com/ScriptReference/GameObject.FindGameObjectsWithTag.html The Problem is that it wont work at all! I get target with the function, but not the closest one, just the one that has been spawned first in the scene. After I hit it, the target switches to the second one that spawend. I only call the FindClosestEnemy(). It's returning an Enemy, but not the right one. I just wan't to have this work to finalize this project. this is very frustrating. I don't have time, ether I get it working within the next hours, or it won't be in there at all.
Your answer
Follow this Question
Related Questions
How can I make an object transform to given position and rotation 2 Answers
Transform shows in Scene View on Runtime, but not in Camera (also: Vive Trackers) 0 Answers
How to keep track of multiple NPC's / Enemies 0 Answers
How do I code transform translate in unity3d/ Not working right 0 Answers
transform.lookat not working? 0 Answers