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 Harrykotiej · Jul 16, 2014 at 06:58 PM · rtsattacking

How to combine FindGameObjectsWithTag with AttackScript

Hi, I'm a student and quite new with coding in C#. I've tried many times to make a script for my RTS in which spawned prefab units all called "Konijn" (rabbit in Dutch) in the team you play can transform.find all the already existing enemies in the scene with the tag "beer" (bear in Dutch).

The script I used didn't help at all. A unit could only attack one bear at a time until the bear dies. So I searched for a different script that could work but don't know how to combine it with the script I already have. Can someone help this newbie out a bit?

SCRIPT THAT DIDN'T WORK CORRECTLY:

 using System.Collections;
 public class BunnyAttack : MonoBehaviour {
     
     // Set player GameObject as the target in the inspector
     public GameObject tag; 
     
     // Holds the enemy object's active attack delay timer
     public float attackDelay;
     
     // Holds the enemy object's attack cooldown
     public float coolDown;
     
     // Holds the enemy object's attack range
     public float attackRange;
     
     // Holds how much damage the enemy object does per atk 
     private int attackPower;    
     
     void Start () {
         if (tag == null)
             tag = GameObject.FindGameObjectsWithTag("beer")[0];
         
         attackDelay = 0; 
         coolDown = 2.0f;
         attackRange = 3.5f;
         
         // Use a negative number for attackPower 
         // The current health updated logic is 
         // (currentHealth += attackpower)
         attackPower = -10; 
     }
     
     void Update () {
         // Checks if the enemy object can attack.
         AttackDelayTimer(); 
         if (tag == null)
             tag = GameObject.FindGameObjectsWithTag("beer")[0];
     }
     
     private void AttackDelayTimer(){
         if (attackDelay > 0){
             // If attackDelay is greater then 0,
             // Reduce attackDelay by 1 second per cycle
             attackDelay -= Time.deltaTime;
         }
         
         if (attackDelay < 0){ 
             // Prevents attackDelay from ever becoming less than zero
             attackDelay = 0;
         }
         
         if (attackDelay == 0) {
             // Sets attackDelay to = coolDown to force delay between atk
             attackDelay = coolDown;
             
             // Allow an attack
             Attack(); // handles object's attacking.
         } 
     }
     
     private void Attack() {
         // Calculates the distance between the enemy object and it's target
         float distanceFromTarget = Vector3.Distance 
             (tag.transform.position, transform.position);
         
         if(distanceFromTarget < attackRange) { 
             // Checks if the target is within attack range
             // Loads the target's PlayerHealth script
             HealthBarEmpty playerHP = (HealthBarEmpty)
                 tag.GetComponent("HealthBarEmpty");
             
             // Sends an attack update to the PlayerHealth script
             // to reflect the attack
             attackPower= -20;
             playerHP.AddjustCurrentHealth(attackPower);
         }
         if(distanceFromTarget > attackRange) { 
             // Checks if the target is within attack range
             // Loads the target's PlayerHealth script
             HealthBarEmpty playerHP = (HealthBarEmpty)
                 tag.GetComponent("HealthBarEmpty");
             
             // Sends an attack update to the PlayerHealth script
             // to reflect the attack
             attackPower = 0;
         }
     }
 }

THE CODE THAT COULD HELP ME OUT AND I DON'T KNOW WHERE TO PLACE IN THE SCRIPT ABOVE:

 foreach(GameObject beerObj in GameObject.FindGameObjectsWithTag("beer"))
 {
     if(beerObj.name == "beer")
     {
         //Do Something
     }
 }
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 robertbu · Jul 17, 2014 at 03:10 PM

Get rid of all declarations, references or assignments to the 'tag' variable outside of the Attack() method. Then you can do this to Attack():

 private void Attack() {
     foreach(GameObject tag in GameObject.FindGameObjectsWithTag("beer"))
     {
         // Calculates the distance between the enemy object and it's target
         float distanceFromTarget = Vector3.Distance 
             (tag.transform.position, transform.position);
         
         if(distanceFromTarget < attackRange) { 
             // Checks if the target is within attack range
             // Loads the target's PlayerHealth script
             HealthBarEmpty playerHP = (HealthBarEmpty)
                 tag.GetComponent("HealthBarEmpty");
             
             // Sends an attack update to the PlayerHealth script
             // to reflect the attack
             attackPower= -20;
             playerHP.AddjustCurrentHealth(attackPower);
         }
         if(distanceFromTarget > attackRange) { 
             // Checks if the target is within attack range
             // Loads the target's PlayerHealth script
             HealthBarEmpty playerHP = (HealthBarEmpty)
                 tag.GetComponent("HealthBarEmpty");
             
             // Sends an attack update to the PlayerHealth script
             // to reflect the attack
             attackPower = 0;
         }
     }
 }

Note that all I've done is to nest the existing code inside of the foreach. I change the name of the variable in the foreach to 'tag'. Note given your foreach code, I've assume that you want to attack every 'beer' that is within range. I would take a slight change if you wanted a random 'beer', and a more significant change to attack the closest 'beer'.

Comment
Add comment · Show 1 · 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
avatar image Harrykotiej · Jul 18, 2014 at 07:43 PM 0
Share

Thank you for answering. I found a different solution but this one seems to work as well.

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

2 People are following this question.

avatar image avatar image

Related Questions

How to calculate attack speed 1 Answer

RTS Style Camera Scrolling 8 Answers

Is a Unity simulation deterministic? 4 Answers

Rts people select 2 Answers

How to check hit on tank 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