• 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 Mikez · Jul 05, 2012 at 06:49 PM · attackfindgameobjectswithtagclosest

Making a script send a message to the "closest" enemy

I am developing a script which enables a player to attack GameObjects tagged "enemy". The issue I am trying to resolve is the ability to produce damage towards any closest "Enemy" object, instead of one GameObject after another. At this stage, I am only able to murder a specific tagged object, instead of any closest tagged object. Here is a chunk of the script related to my issue (the center of problem is marked in arrows):

function Update () {

InvokeRepeating("FindClosestEnemy", 0, scanFrequency); }

 function FindClosestEnemy() : GameObject {
 
  var gos : GameObject[];
  gos = GameObject.FindGameObjectsWithTag("Enemy");
  var closest : GameObject;
  var distance = Mathf.Infinity;
  var position = transform.position;
  
  for (var go : GameObject in gos) {
  var diff = (go.transform.position - position);
  var curDistance = diff.sqrMagnitude;
  
  if (curDistance < distance) {
  closest = go;
  distance = curDistance;
  
  SendMessage("CloseEnemy", closest); //State name variable?
  
        }
     }
  return closest;
 }



  function CloseEnemy(closest)
     
     {
   

  

-> closest : String = gameObject.name;

-> Target = GameObject.FindWithTag("Enemy");

  var distance = Vector3.Distance(Target.transform.position, transform.position);
  
  var dir = (Target.transform.position - transform.position).normalized;
  
  var direction = Vector3.Dot(dir, transform.forward);
 
  
  if (Input.GetKeyDown("q")){
  
  if ( distance < 5){
  
  if ( direction > 0){
  
  var script = Target.GetComponent(EnemyHealthDraw);
  
  script.punchDmg(PunchDamage); 
  
  }
  
  }
  
  } 
 

}

There is a function which is triggered after SendMessage("CloseEnemy", closest). I was happy with this, because print(closest); registered the name of the "closest" enemy object, however I failed to convert the variable "closest" into a string, which could be used for GameObject.Find(string);. In place of string, I inserted "enemy". If you can answer this problem, it will help me a lot! Thanks.

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 Kryptos · Jul 05, 2012 at 07:33 PM 0
Share

For optimization, don't calculate the distance and the normalized vector. Because you're doing twice the same calculation (which uses an expensive square root).

Ins$$anonymous$$d do that:

 var v3Diff = (Target.transform.position - transform.position);
 var distance = v3Diff.magnitude;
 var dir = v3Diff/distance;
avatar image Mikez · Jul 05, 2012 at 08:05 PM 0
Share

wow, thanks man!!

1 Reply

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

Answer by Owen-Reynolds · Jul 05, 2012 at 08:36 PM

After running the loop in FindClosestEnemy, your gameObject variable closest is the nearest enemy. You can completely delete the two lines you have marked and replace them with: Target=closest;.

Secondly, that's a standard "Price is Right" loop. It looks at enemies one at a time, making closest always be the nearest enemy so far. It can set closest multiple times, as it sees more enemies. So, the SendMessage should be moved to after the loop, instead of being in it.

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 Mikez · Jul 06, 2012 at 01:30 AM 0
Share

Thanks, your tips have helped me find a problem. The script is running perfectly!! except punchDmg is multipled. I suspect this is due to lag in the script? I increased frequency and delay in InvokeRepeated, which makes this effect less multiplied.

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.

Welcome to Unity Answers

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.



Follow this Question

Answers Answers and Comments

7 People are following this question.

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

Related Questions

Find Closest GameObject in a players vicinity 1 Answer

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

Game lagging while looking for closest Enemy 2 Answers

Finding closest object to player 3 Answers

geting the closest object from a array 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