Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
12 Jun 22 - 14 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 CannJRB · Dec 05, 2016 at 07:14 AM · c#2dtrigger

Is Random.Range in this script causing performance issues?

Hi, I'm definitely new to this and feel like I must be causing a dramatic frame rate drop with the following script:

 using UnityEngine;
 using System.Collections;
 
 public class Enemy1Controller : MonoBehaviour
 {
 
     GameObject player;
     public static float speed = 0.07f;
     Vector3 playerPosition;
     bool waitForCrowd;
     float waitTimer;
     float waitForCrowdCoolDown;
     public CircleCollider2D enemyProximityTrigger;
 
     void Start()
     {
         waitForCrowd = false;
         waitForCrowdCoolDown = 3;
         waitTimer = 0.5f;
         player = GameObject.Find("Player");
     }
 
     void Update()
     {
         CrowdCoolDown();
         Movement();
     }
 
     public void Movement()
     {
         if (waitForCrowd)
         {
             FightCrowd();
         }
         else
         {
             //Follows player
             playerPosition = player.transform.position;
             transform.position = Vector3.MoveTowards(transform.position, playerPosition, speed);
         }
     }
 
     public void FightCrowd()
     {
         //Pauses after trigger and cool down then bounces in a random direction
         waitTimer -= Time.deltaTime;
         if (waitTimer < 0)
         {
             int setRandDir = (int)Random.Range(0, 3);
             switch (setRandDir)
             {
                 case 0:
                     transform.Translate(0.2f, 0.0f, 0.0f);
                     Debug.Log("Left");
                     break;
                 case 1:
                     transform.Translate(0.0f, 0.2f, 0.0f);
                     Debug.Log("Up");
                     break;
                 case 2:
                     transform.Translate(-0.2f, 0.0f, 0.0f);
                     Debug.Log("Right");
                     break;
                 case 3:
                     transform.Translate(0.0f, -0.2f, 0.0f);
                     Debug.Log("Down");
                     break;
             }
             waitTimer = 0.5f;
             waitForCrowdCoolDown = 3;
             waitForCrowd = false;
         }
     }
 
     public void CrowdCoolDown()
     {
         waitForCrowdCoolDown -= Time.deltaTime;
         Debug.Log(waitForCrowdCoolDown);
     }
 
     void OnTriggerStay2D(Collider2D other)
     {
         Debug.Log("Triggered");
 
         if (waitForCrowdCoolDown <= 0)
         {
             //Reduces frequency of crowd interaction and not all react at the same time
             if (Random.Range(1f, 10f) < 2)  //Are too many of these at once to much to process?
                 waitForCrowd = true;
         }
         Debug.Log(waitForCrowd);
     }
 }

What happens here is many these "Enemy1" prefabs are Instatiated by a timer in another script. When they collide with each other while chasing the player, they have a chance of pausing for a moment and getting bumped around. When too many collisions are happening at once, the frame rate can plummet to single digits.

It is just a bunch of circle sprites chasing a square. It seems like when 4 to 6 of the circles are touching each other, that's when the frame rate drops to unbearable levels.

I was thinking the culprit might be the RNG being called so often but if anyone can point me in a better direct to get these results I would really appreciate it.

Comment
Add comment · Show 6
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 CannJRB · Dec 06, 2016 at 01:40 AM 0
Share

The short answer is "No." When I remove the random numbers and set those variables, it still runs just as slow.

The only thing that prevents the frame rate drop is disabling the triggers. What seems to help somewhat is changing OnTriggerStay2D to OnTriggerEnter2D. The trigger doesn't go off as often and I get similar results but performance still drops dramatically.

avatar image getyour411 CannJRB · Dec 06, 2016 at 01:42 AM 0
Share

Please do not post a follow-up as an Answer. I converted this one for you.

avatar image getyour411 CannJRB · Dec 06, 2016 at 02:05 AM 0
Share

Cache transforms in Start to avoid implicit 'Search' per frame. Line 49 will never select 3 (Random.Range Int is exclusive). 88 is using float syntax with the 'f'. 13 is declared but not used. Turn on the Profiler and see.

avatar image Bunny83 getyour411 · Dec 06, 2016 at 02:42 AM 0
Share

Caching the transform component is a micro optimisation that's not worth mentioning unless you use it like 10000 times per frame. Anyways good catch at line 49. Line 88 is ok that way, however it's probability is frame-rate dependent.

Show more comments
avatar image Commander-Rabbit · Dec 06, 2016 at 02:33 AM 0
Share

If anything is called to much except for methods, floats and bools i usually get a huge framerate drop

2 Replies

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

Answer by Bunny83 · Dec 06, 2016 at 02:35 AM

No. Random.Range is extremely fast as Unity uses Xorshift128. What is most likely the biggest performance hit is all those Debug.Log statements. Those are like 100000 times slower than Random.Range. You effectively are printing three Debug.Logs "per frame" when you currently collide with something, otherwise just one per frame. You should remove them all when you're done debugging.

Debug.Log() / print() are extremely slow, especially inside the editor. You should use them only for debugging and avoid to call them every frame.

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 Spartiate0033 · Dec 06, 2016 at 02:51 AM 0
Share

Pretty much this. Debug.Log is a killer on performance. To add onto Bunny83's comment, I highly recommend you use Unity's built in FPS script and print your FPS to screen at all times. That way, you can see the change in performance throughout the life of the program.

avatar image CannJRB · Dec 07, 2016 at 06:19 AM 0
Share

Wow. I've read comments and threads about removing Debug.Log before building but I did not realize the impact it really had. I just removed them and let the game spawn more than 2 dozen enemies and never saw the frame rate drop below 60 FPS.

avatar image
0

Answer by joebopie · May 09 at 04:10 PM

Random.Range is Very slow in unity, i had to switch them all out for UnityEngine.Random.Range.

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 Bunny83 · May 09 at 07:19 PM 0
Share

I don't quite get what you want to tell us here. The OP used UnityEngine.Random.Range since he imported the UnityEngine namespace and not the System namespace.

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

10 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

Related Questions

Script calling onCollisionEnter2D and onTriggerEnter2D while disabled 1 Answer

Triggers Interacting with Triggers 0 Answers

How to detect in grid of objects if one is destroyed while beside adjacent objects without rigidbody? 1 Answer

Text on Enter Trigger / Text Delay 1 Answer

X number of collisions for destroy 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