Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 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 /
  • Help Room /
avatar image
0
Question by ThatGuy52699 · Aug 23, 2021 at 06:09 PM · variablehierarchyfind-gameobject

Trouble killing closest enemy

Hi! I'm currently working on my first game, a quick-time game where enemies spawn with letters on top of them which the player presses the corresponding key to kill the enemy. I want it so the player can only kill the closest enemy to it, which I have set up to find. The problem is that the "killKey" doesn't lineup to the closest enemy, but rather the enemy that recently spawned. I'm fairly certain that the find closest enemy part of my script does indeed work (as shown by the debug.drawline). Heres my script: Player:

 public class Player : MonoBehaviour
     {
         public string keyPressed;
         public int penaltyTimer;
         public GameObject target;
     
     
         // Start is called before the first frame update
         void Start()
         {
         }
     
         // Update is called once per frame
         void Update()
         {
             var allKeys = System.Enum.GetValues(typeof(KeyCode)).Cast<KeyCode>();
             FindClosestEnemy();
     
            
             if (Input.GetKeyDown("w") || Input.GetKeyDown("a") || Input.GetKeyDown("s") || Input.GetKeyDown("d"))
             {
                 
                 foreach (var key in allKeys)
                 {
                     if (Input.GetKeyDown(key))//finds what key the player pressed
                     {
                         Debug.Log(key + " was pressed.");
                         keyPressed = key.ToString();
                     }
                 }
                 
                 SwordStrike();
             }
         }
     
         void FindClosestEnemy()
         {
             float distanceToClosestEnemy = Mathf.Infinity;
             GameObject closestEnemy = null;
             GameObject[] Allenemies = GameObject.FindGameObjectsWithTag("Enemy");
     
             foreach (GameObject currentEnemy in Allenemies)
             {
                 float distanceToEnemy = (currentEnemy.transform.position - this.transform.position).sqrMagnitude;
                 if (distanceToEnemy < distanceToClosestEnemy)
                 {
                     distanceToClosestEnemy = distanceToEnemy;
                     closestEnemy = currentEnemy;
                 }
                 target = closestEnemy;
                 Debug.DrawLine(this.transform.position, target.transform.position);
             } 
             
         } 
             
     
         void SwordStrike()
         {
             if (target.GetComponent<EnemyMovement>().killKey == keyPressed)
             {
                 Object.Destroy(target.gameObject);
             }
             
         }
     }

Enemy:

 public class EnemyMovement : MonoBehaviour
 {
     public float speed;
     private Transform objective;
     public GameObject Letter;
     public string killKey;
 
     void Start()
     {
         objective = GameObject.FindGameObjectWithTag("Player").transform;
         GetRandomLetter();
     }
 
     // Update is called once per frame
     void Update()
     {
 
         //move towards objective
         transform.position = Vector2.MoveTowards(transform.position, objective.position, speed * Time.deltaTime);
 
         if (Vector2.Distance(transform.position, objective.position) < .5)//if enemy hits player
         {
             Destroy(this.gameObject);
         }
         
     }
 
     void GetRandomLetter()
     {
         string[] wLetter = { "W", "A", "S", "D" };
         int randomLetter;
         randomLetter = UnityEngine.Random.Range(0, wLetter.Length);
         killKey = wLetter[randomLetter];
         if (Letter)
         {
             GameObject Text = Instantiate(Letter, transform.position, Quaternion.identity);
             Text.transform.parent = gameObject.transform;//sets as parent
         }
         Letter.GetComponent<TextMesh>().text = killKey;
 
     }
 
     
 }

Thanks in advance!

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
Best Answer

Answer by ThatGuy52699 · Sep 18, 2021 at 02:31 AM

I found out the issue. I thought I checked it but the letter on the enemy was different from the variable Key on the enemy. it works now though. All I did was move up the Letter.GetComponent line above the if statement.

  void GetRandomLetter()
         {
             string[] wLetter = { "W", "A", "S", "D" };
             int randomLetter = UnityEngine.Random.Range(0, wLetter.Length);
             Key = wLetter[randomLetter];
             Letter.GetComponent<TextMesh>().text = Key;
             if (Key != null)
             {
                 if (Letter)
                 {
                     GameObject Text = Instantiate(Letter, transform.position, Quaternion.identity);
                     Text.transform.parent = gameObject.transform;//sets as parent
     
                 }
                 
             }
 
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

168 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 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 avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Why the values in the hierarchy and the values in the code are different ? 0 Answers

Why would Hierarchy selection impact game behavior? 1 Answer

Problem with player Score 1 Answer

Use enum hidden value as something other than int? (C#) 2 Answers

Adding to variable only once? 0 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