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
1
Question by konsowa · Jul 03, 2012 at 03:46 PM · looplag

How would i make this code not lag the game

  void GetNearestMinion()
     {
         foreach (GameObject Minion in EnemyMinions)
         {
             float finishTime = Time.time + waitTime;
             MinionsTransforms.Add(Minion.transform);
             
         }
         MinionsTransforms.Sort(delegate(Transform t1, Transform t2) { return (Vector3.Distance(t1.position, t2.position).CompareTo(Vector3.Distance(t2.position, transform.position))); });
         
         nearestMinion = MinionsTransforms[0].gameObject;
     }


How can i stop this from lagging the game keep in mind that every minion does this check at least once every frame(which i don't mind reducing)?

Comment
Add comment · Show 5
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 ThePunisher · Jul 03, 2012 at 04:17 PM 1
Share

So you have every $$anonymous$$ion getting every other $$anonymous$$ion's transform, and on top of that sorting it? Not sure you can make that not lag your game. What are you trying to achieve here? $$anonymous$$aybe we can find a different way of achieving the same behavior.

avatar image Luci85 · Jul 03, 2012 at 04:50 PM 1
Share

If you are searching for the nearest $$anonymous$$ion, why not just use Vector2(or .3).Distance?

avatar image konsowa · Jul 03, 2012 at 04:56 PM 0
Share

trying to sort $$anonymous$$ions by distance and get the first one in the array

avatar image Bunny83 · Jul 03, 2012 at 05:04 PM 0
Share

btw, how often do you call this function?

avatar image ThePunisher · Jul 03, 2012 at 05:58 PM 0
Share

From what it sounds Bunny83, it seems like he calls that for every unity every frame so I can see why it lags.

1 Reply

· Add your reply
  • Sort: 
avatar image
3

Answer by Bunny83 · Jul 03, 2012 at 05:03 PM

There are several things not very efficient here:

  • Sorting the whole array is totally unnecessary. You just want the closest.

  • You should hold an array with the transform references so you don't need to get each transform everytime.

  • Just do a simple min distance search that compares the squared distance. This is much faster than calculating the true distance. The relations stay the same.

Something like that:

 Transform GetNearestMinion()
 {
     Transform nearestMinion = null;
     Vector3 myPos = transform.position;
     float minDist = 999999;
     foreach (Transform Minion in EnemyMinions) // EnemyMinions is now a Transform array or List
     {
         float dist = (Minion.position - myPos).sqrMagnitude;
         if (dist < minDist)
         {
             minDist = dist;
             nearestMinion = Minion;
         }
     }
     return nearestMinion;
 }

This is the most optimised way. ps, i've written that from scratch, so there might be typing mistakes ;)

This function now returns the nearest Minion or null if there is none at all.

Comment
Add comment · Show 12 · 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 konsowa · Jul 03, 2012 at 05:16 PM 0
Share

If i have 10 $$anonymous$$ions doing this at the same time every frame that would definitely make the game lag rite?

avatar image konsowa · Jul 03, 2012 at 05:17 PM 0
Share

Oh and the $$anonymous$$ions move which is y i need to get the transforms a lot, think of League of Legends when answering and how that game works

avatar image Bunny83 · Jul 03, 2012 at 05:27 PM 0
Share

Well, if you have just 10, your code shouldn't be that slow. However, Unity, or LINQ uses

Quicksort so it get's quickly worse. Your method needs in the worst case 100 comparisions for 10 elements. If you have 40 elements it would be 1600 comparisions. Each of your comparisions calulates the distance two times. The distance calculation requires a square-root, which is almost the slowest arithmetic operation that exist (besides Pow).

$$anonymous$$y function doesn't use any square root, just float multiplications / additions and you only have to check each $$anonymous$$ion once since you just need the nearest and not the whole array sorted...

Btw, does every $$anonymous$$ion execute this, or just you, the player? If it's executed for every $$anonymous$$ion that would really be crazy... That's x^3 in the worst case. For 10 $$anonymous$$ions that would be 1,000 comparisons per frame... and for 100 $$anonymous$$ions that would be 1,000,000

avatar image konsowa · Jul 03, 2012 at 05:41 PM 1
Share

Well the thing is i have 5 spawning for each $$anonymous$$m every 15 seconds which means there will be more than 10 And Yes every $$anonymous$$ion does it..The thing is im not too woried about calculations what im worried about is the foreach loop isnt that slowing things up?

Did you mean sqr$$anonymous$$agnitude in that code up there ins$$anonymous$$d of sqrDistance?

avatar image Wolfram · Jul 03, 2012 at 06:07 PM 1
Share

A foreach loop per se doesn't make things slow, it entirely depends what happens in the loop. @Bunny83's approach is exactly right. While you actually sorted the whole array, which is extremely expensive but totally irrelevant, he just loops through the transforms and finds the closest one. He uses sqr$$anonymous$$agnitude (yes, there is no sqrDistance), which does not use an expensive $$anonymous$$athf.Sqrt(), and the simple loop with an O(n) is much faster especially for a large number of elements, than a quicksort algorithm, which needs at least O(n * log n) to sort the array.

Show more comments

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

8 People are following this question.

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

Related Questions

Look not responsive enough 0 Answers

Variable declaration, what's faster/more efficient? 1 Answer

Audio not looping. 2 Answers

Create objects in a selected area 2 Answers

Audio Lag Between Multiple Listeners 0 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