Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by Seppi · Jan 14, 2018 at 12:39 AM · programming

Target the closest enemy?

So I'm trying to find the enemy that's closest to the player out of a group of enemies. It doesn't seem to be targeting properly. What am I doing wrong?

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class CombatController : MonoBehaviour {
 
     GameObject[] enemies;
     GameObject player, target;
     int enemyCount;
     float distance;
 
     void Start () {
 
         distance = 100;
 
         player = GameObject.Find("Player");
     }
 
     // Update is called once per frame
     void Update () {
 
         enemies = GameObject.FindGameObjectsWithTag("Enemy");
 
         for(int i = 0; i < enemies.Length; i++){
 
             if(Mathf.Abs(Vector2.Distance(player.transform.position, enemies[i].transform.position)) < distance){
 
                 distance = Mathf.Abs(Vector2.Distance(player.transform.position, enemies[i].transform.position));
 
                 target = enemies[i];
                 Debug.Log(target);
 
                 player.GetComponent<PlayerMovement>().closestEnemy = target.transform.position;
             }
         }
     }
 }
 
Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by MJV314 · Nov 09, 2020 at 06:31 PM

So I am still learning unity, and C# coding within unity, but I have fixed your code. I'm not sure how to explain it, but you can look at your code versus mine and figure out what I did.

  using System.Collections;
  using System.Collections.Generic;
  using UnityEngine;
 
 public class CombatController : MonoBehaviour
 {
     private GameObject[] enemies;
     public Player player; //this assumes that your player script is named "Player"
     private int enemyCount;
     private float distance = 100f;
     private GameObject target;
 
     void Update()
     {
         enemies = GameObject.FindGameObjectsWithTag("Enemy");
 
         for (int i = 0; i < enemies.Length; i++)
         {
             if (Vector2.Distance(player.transform.position, enemies[i].transform.position) < distance)
             {
                 distance = Vector2.Distance(player.transform.position, enemies[i].transform.position);
 
                 target = enemies[i];
 
                 player.targetEnemy = target.transform; // your Player script needs to have a "public Transform targetEnemy;"
             }
 
             //this prevents a nasty loop that causes the minimum range for a target to be chosen to become shorter and shorter
             if (Vector2.Distance(player.transform.position, enemies[i].transform.position) > distance)
             {
                 distance = Vector2.Distance(player.transform.position, enemies[i].transform.position);
             }
         }
     }
 }

After fixing the main problem, I noticed you had a secondary issue in the code. Each time an enemy becomes the target the "Distance" becomes the distance between you and the target. Now this should be good, you want to target the closest enemy. But that distance becomes fixed, so if the original target moves away from the player a new closer target would not be targeted unless it moved closer than the ORIGINAL distance to the first target.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

79 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Multiple Cars not working 1 Answer

Make something arrive at position in exactly X seconds? 2 Answers

Changing Enemy Prefab Variable (MoveSpeed) at Runtime 1 Answer

Programming custom objects instead of using GameObjects 0 Answers

Find a game object using the value of a variable in the script attached to it, or with it's transform.position? 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges