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 /
avatar image
0
Question by dwillsc · Apr 21, 2015 at 02:25 PM · enemytargetattackclosesttower

Is this the most efficient way to attack the closest enemy?

BLUF: Is the C# code listed below an efficient way to attack the closest enemy?

Hello all,

I am an experienced level designer and took the plunge into unity about five days ago. I work full time so have only had about 20 hours of messing around with scripts in unity. My experience with programming prior to this was very minimal. I could look at basic code and more or less understand what was trying to be accomplished. I am currently going to be working on dozens of small projects to understand how to accomplish core fundamentals and basic tasks that most games contain.

The current one I am working on is basically this:

I have a turret in the center of an open field

Enemies (zombies... generic, I know) spawn at 4 points (north, south, east, and west) in 3 second intervals

The enemies move at a slow speed towards the turret

Once they are within range, the turret damages the closest enemy (that is within range).

I left a lot of variables public so I can monitor their status in the inspector while the scene plays.. so ignore that.

Please review this bit of code and tell me if there is a more efficient way to attack the closest enemy within range. It works as intended and I haven't noticed any issues with it.

 using UnityEngine;
 using System.Collections;
 
 public class Attack_Enemy : MonoBehaviour
 {
     public Vector3 playerPosition;                // Default 0, 0, 0.  Turret is in center of scene, value not needed.
     public Vector3 distanceDifference;            // Difference between the target and turret.
     public float oldDistance = Mathf.Infinity;    // Starts at infinity to always ensure IF loop runs to detect closest enemy.
     public float currentDistance;                // The sqrMagnitude of the difference in distance
     public float attackSpeed;                    // The rate of attack of the turret
     public float timer;                            // A timer that constantly runs
     public int attackDamage;                    // The amount of damage the turret does
     public GameObject enemy;                    // Current closest enemy
     public GameObject closest;                    // Assigned as closest target
     public GameObject[] targets;                // Array to load every target as they enter trigger
     public bool enemyInRange;                    // True/False if the enemy is within the trigger or not
     HealthZombie HealthZombie;                    // To adjust health of zombie from the HealthZombie script
 
     void OnTriggerEnter (Collider other)
     {
         if (other.gameObject.tag == "Enemy")
         {
             enemyInRange = true;
             targets = GameObject.FindGameObjectsWithTag ("Enemy");
             foreach (GameObject target in targets)
             {
                 distanceDifference = target.transform.position - playerPosition;
                 currentDistance = distanceDifference.sqrMagnitude;
                 if (currentDistance < oldDistance)
                 {
                     closest = target;
                     enemy = closest;
                     HealthZombie = enemy.GetComponent <HealthZombie> ();
                     oldDistance = currentDistance;
                 }
             }
             oldDistance = Mathf.Infinity;
         }
     }
 
     void OnTriggerExit (Collider other)
     {
         if (other.gameObject.tag == "Enemy")
         {
             enemyInRange = false;
         }
     }
 
     void Update()
     {
         timer += Time.deltaTime;
         if (timer >= attackSpeed && enemyInRange && HealthZombie.currentHealth > 0)
         {
             Attack ();
         }
     }
 
     void Attack ()
     {
         timer = 0f;
         HealthZombie.TakeDamage (attackDamage);
     }
 }

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

0 Replies

· Add your reply
  • Sort: 

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

3 People are following this question.

avatar image avatar image avatar image

Related Questions

Need Help With My AI Script 1 Answer

Attack/Targeting Script Issue 1 Answer

Enemy attack target 1 Answer

Attacking enemy script problem 0 Answers

Closest target acquisition using Physics Overlap Sphere script not working 1 Answer


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