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 Stealthygolem · Oct 20, 2014 at 10:58 AM · c#2denemytarget

C#2d Attacking multiple enemies rather than one

Hello! I have a list of enemies currently on the map. And my player will target the one that's closest to him. Problem is, I want to make the player target more than one of the enemies if they are in attack range of the player. Right now I'm just targetting one at the time, so I guess that's where the fault lies. How do I go about making my targets potentially multiple? Relevant code for enemy list:

     private GameObject target;

     //List-array to find enemies
     GameObject FindClosestEnemy() {
         GameObject[] gos;
         gos = GameObject.FindGameObjectsWithTag("Enemy");
         GameObject closest = null;
         maxDistance = 50f;
         Vector3 position = transform.position;
         foreach (GameObject enemy in gos) {
             Vector3 diff = enemy.transform.position - position;
             float curDistance = diff.sqrMagnitude;
             if (curDistance < maxDistance) {
                 closest = enemy;
                 maxDistance = curDistance;
             }
         }
         return closest;
     }

Then I declare before the player attack: GameObject target = FindClosestEnemy();

I hope you can bare with me, and I appreciate any help. I am still quite inept, haha!

Comment
Add comment · Show 2
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 Wisearn · Oct 20, 2014 at 11:04 AM 0
Share

What you want is an array of enemies that are close enough and then return the array which you can then do a foreach attack on.

One way of doing it with your current script is to do a "for (int i = 0" loop ins$$anonymous$$d of foreach and when an enemy is too far you remove from gos[] list and do i--; and then return gos at the end ins$$anonymous$$d of closest.

And of course then change your player attach so it does attack on each item in the array.

avatar image Stealthygolem · Oct 20, 2014 at 11:14 AM 0
Share

I appreciate your help, but I am a bit confused as to how to go about doing this. Could you either be a bit more detailed, or show me where I can learn more about what you are trying to tell me? Thanks!

2 Replies

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by HarshadK · Oct 20, 2014 at 11:12 AM

You can create a List of closest enemies to store the close enemies. So your method for finding close enemies become:

 List<GameObject> FindCloseEnemies() {
      GameObject[] gos;
      gos = GameObject.FindGameObjectsWithTag("Enemy");
      // We store the close enemies in the list
      List<GameObject> closest = new List<GameObject>();
      maxDistance = 50f;
      Vector3 position = transform.position;
      foreach (GameObject enemy in gos) {
          Vector3 diff = enemy.transform.position - position;
          float curDistance = diff.sqrMagnitude;
          if (curDistance < maxDistance) {
             // We add the enemy to the list if it is close
             closest.Add(enemy);
          }
      }
      return closest;
  }
  

And you can call this like:

  List<GameObject> closeEnemies = FindCloseEnemies();

Now you can process your closeEnemies list to perform the operation of attack or anything else since it contains the close enemies.

Comment
Add comment · Show 10 · 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 Stealthygolem · Oct 20, 2014 at 11:30 AM 0
Share

I changed my list to look like this. First of it complained about a syntax error on line: List closest = new List; . So I changed it to List closest = new List();. Was that correct? I also replaced my GameObject target = FindClosestEnemy(); with your List closeEnemies = FindCloseEnemies(); but to no avail. Now I don't get any errors, but I can't attack any enemies now. What am I likely doing wrong?

Do you think it has something to do with this? Because I am looking for "target" in enemyscript.

                 if(maxDistance <= 50f) {
                     EnemyHealth eh = (EnemyHealth)target.GetComponent("EnemyHealth");
                     eh.curhp -= 10;



EDIT: Seems like the codeblock here in comments doesn't allow alligator mouths! Hope you still understand :)

avatar image HarshadK · Oct 20, 2014 at 11:41 AM 0
Share

You need to include

 using System.Collections.Generic;

for List to work.

The code that I provided is correct just check it with this above statement added to your code.

avatar image Stealthygolem · Oct 20, 2014 at 11:46 AM 0
Share

I have already included Generic, so that can't be it.

avatar image HarshadK · Oct 20, 2014 at 11:50 AM 0
Share

With the list you should always use the type like:

List;

As I've done in my code above. Use it as it is and then let me know.

avatar image HarshadK · Oct 20, 2014 at 12:33 PM 1
Share

It is edited in the answer.

Also since you are using a list you need to iterate through each enemy object to reduce its health. In below script I'm using closeEnemies list as it is in continuation of the code snippet I provided.

 foreach(GameObject closeEnemy in closeEnemies)
 {
     if(maxDistance <= 50f) {
          EnemyHealth eh = (EnemyHealth)closeEnemy.GetComponent("EnemyHealth");
          eh.curhp -= 10;
     }
 }
Show more comments
avatar image
0

Answer by Raven-Rock · Oct 20, 2014 at 11:30 AM

Try something like the follow.... i think another person above mentioned something along these lines as well.

 public  Gameobject findClosest(Gameobject[] enemies)
             {
                 float minDistanceTargClosest=100;
                 Gameobject closest=null;
                 Vector3 myPosition = transform.position;
                 
                 for (int a=0; a<enemies.Length;a++)
                 {
 
                     float distance = Vector3.Distance (myPosition, enemies[a].transform.position);
     
                     if(distance<minDistanceTargClosest)
                     {
                             minDistanceTargClosest=distance;
                             closest=enemies[a];
                     }
                 }
                 return closest;
             }






Comment
Add comment · Show 2 · 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 Stealthygolem · Oct 20, 2014 at 11:37 AM 0
Share

This gives me a strange syntax error on the distance variable being called. I tried to declare the variable, but that didn't work either. Anything syntactically wrong with your code, or am I missing something crucial for it to work?

avatar image Raven-Rock · Oct 20, 2014 at 11:42 AM 0
Share

sorry about that :) I pulled it straight from one of my scripts and didn't change everything needed. Try it now.

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

29 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

Related Questions

my enemy is broken 1 Answer

Multiple Cars not working 1 Answer

2d c# boss follow code 0 Answers

Enemy bounce from screen edges 0 Answers

Distribute terrain in zones 3 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