Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 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
1
Question by 3dDude · Apr 16, 2010 at 12:50 AM · arraydistanceclosest

geting the closest object from a array

hi i am making a tower defense game and i am working on the towers and i have a script that fills a array with all the enemies in the scene. but i want to know how to find the closest object in the array can anyone mod my script to work like that? here it is:

var target : Transform; var enemies : GameObject[]; function Update () { enemies = GameObject.FindGameObjectsWithTag("enemy"); transform.LookAt(target);

}

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

2 Replies

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

Answer by Michael La Voie · Apr 16, 2010 at 12:57 AM

You'll need to use Vector3.Distance:

var target : Transform; var enemies : GameObject[];

function Update () { enemies = GameObject.FindGameObjectsWithTag("enemy"); transform.LookAt(target);

 if(enemies.length > 0) {
     var closestEnemy = enemies[0];
     var dist = Vector3.Distance(transform.position, enemies[0].transform.position);

     for(var i=0;i<enemies;i++) {
         var tempDist = Vector3.Distance(transform.position, enemies[i].transform.position);
         if(tempDist < dist) {
             closestEnemy = enemies[i];
         }
     }

     //do something with the closestEnemy
 }

}

Comment
Add comment · Show 4 · 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 3dDude · Apr 16, 2010 at 01:16 AM 0
Share

thanks a lot i'll try that

avatar image 3dDude · Apr 16, 2010 at 01:18 AM 0
Share

i got this error Assets/Scripts/dartTower.js(12,22): BCE0051: Operator '

avatar image 3dDude · Apr 16, 2010 at 12:56 PM 0
Share

never $$anonymous$$d i fixed the problem :) anyway it works great thanks!

avatar image superventure · Feb 28, 2011 at 11:40 PM 1
Share

for anybody else who gets that error... use for(var i=0; i < enemies.Length; i++) {

avatar image
5

Answer by Eric5h5 · Apr 16, 2010 at 02:00 AM

It's not a good idea to use FindGameObjectsWithTag every frame, because it's slow. It's also a better idea to have enemies be a Transform array instead of a GameObject array, because that way you don't have to get the transform component every time you check the distance of one of them. The enemies array should only be rebuilt when necessary; it may be better to add and remove from an array instead of using Find at all, but that's a little more complicated.

Also, Vector3.Distance is a bit slow because it involves a square root; it's better to use (a-b).sqrMagnitude instead. Since a tower isn't going to move, it's better to store transform.position in a variable so you aren't constantly getting the transform component. As well, it's almost certainly not necessary to get the closest enemy every frame, so try to do that only as often as needed.

var target : Transform; var myPosition : Vector3; var enemies : Transform[];

function Start () { GetEnemies(); myPosition = transform.position; target = FindClosest(enemies); }

function GetEnemies () { var enemyObjects = GameObject.FindGameObjectsWithTag("enemy"); enemies = new Transform[enemyObjects.Length]; for (i = 0; i < enemyObjects.Length; i++) { enemies[i] = enemyObjects[i].transform; } }

function FindClosest (targets : Transform[]) : Transform { var closestDistance = (enemies[0].position - myPosition).sqrMagnitude; var targetNumber = 0; for (i = 1; i < targets.Length; i++) { var thisDistance = (enemies[i].position - myPosition).sqrMagnitude; if (thisDistance < closestDistance) { closestDistance = thisDistance; targetNumber = i; } } return enemies[targetNumber]; }

This way you can call the GetEnemies function only when needed, and the FindClosest function when appropriate (which depends on your game). Since the function takes a Transform array as a parameter, it would be simple to have it check some enemy types but not others, as long as the different enemy types are in different Transform arrays.

Comment
Add comment · Show 3 · 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 pretender · Jun 26, 2010 at 12:33 PM 0
Share

in FindCloseset you pass targets : Transform[] but use enemies : Transform[], what is the deal with that?

avatar image Eric5h5 · Jun 26, 2010 at 03:05 PM 0
Share

@Pretender: what is the deal with what? I don't understand the question.

avatar image Noxury Eric5h5 · Apr 03, 2016 at 03:18 PM 0
Share

@Eric5h5 he meant that you declare a Transform[] parameter "targets", but it is not used inside the function. Ins$$anonymous$$d you use the existing "enemies" array which is not wrong, but in terms you want to call the function to check the distance from another Transform-array (let's say friendlySoldiers[]) it will still give the nearest enemy from enemies[], although you called FindClosest(friendlySoldiers)

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

1 Person is following this question.

avatar image

Related Questions

The name 'Joystick' does not denote a valid type ('not found') 2 Answers

[C#] Buttons through an Array. 1 Answer

A problem with intersection detection 1 Answer

Array empties values on RunTime? 1 Answer

How to access the return value of GameObject.FindGameObjectsWithTag() ? 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