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 jococo · Sep 07, 2013 at 06:03 AM · aicoroutine

CoRoutine help

Hello,

From this post (AI optimization) which attempts to optimize AI by skipping a step via coroutine I tried to set up something similar below.

The code however makes Unity crash. Am I missing something crucial?

  #pragma strict
     
     var MoveSpeed;
     var MaxDist : float;
     var MinDist : float;
     
     public var flyer : int;
     
     
     var normalizedSpeed : float;
     var forwardForce : float;
     
     private var velocity: Vector3;
     
     private var distanceToPlayer : float;
     
     var Player : Transform;
     
     public var character : CharacterController;
     
     private var AI_DELAY: float = 0.5f;
     
     
     
     
     function Start () 
     {
     yield StartCoroutine(AIMovements());
     }
     
     
     function Update () 
     {
     //yield StartCoroutine(AIMovements());
     //StartCoroutine(AIMovements);
     //AIMovements();
     }
     
     function AIMovements () 
     {
     yield WaitForSeconds(Random.value * AI_DELAY);
      while(true) 
      {
         
         var movement = transform.forward;
         
         
         
         if(flyer == 1){
             
             if(distanceToPlayer >= MinDist) {
             if(distanceToPlayer <= MaxDist) {
                 movement *= normalizedSpeed * forwardForce;
                 movement += velocity;    
                 movement *= Time.deltaTime;
                 character.Move( movement );
             }
             }
             
             transform.LookAt(Player);
             
         }
         
         if(flyer == 0){
         
             if(distanceToPlayer >= MinDist) {
             if(distanceToPlayer <= MaxDist) {
                 movement *= normalizedSpeed * forwardForce;
                 movement += velocity;    
                 movement *= Time.deltaTime;
                 movement.y = Player.position.y; // stay on ground
                 character.Move( movement);
                 
                 transform.LookAt(Vector3(Player.position.x, transform.position.y, Player.position.z)); // no rotate up to lookat
             }
             }
         }
     
     
     }
     }


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
1

Answer by ArkaneX · Sep 07, 2013 at 07:16 AM

The cause of your problem is missing yield statement inside while loop. Without it, the loop is infinite and causes Unity to stop responding.

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 jococo · Sep 07, 2013 at 08:43 AM 0
Share

Ok cool thanks, ArkaneX. So I should do something as below?

Strike previous comment out about enemies going grey. I had a misplaced gameObject.SetActiveRecursively(false); ...

However, I am now seeing the frame rate drop over time to nearly 0 from 60 ...

function AI$$anonymous$$ovements () {

  while(true) 
  {
     yield WaitForSeconds(Random.value * AI_$$anonymous$$AY);
     var movement = transform.forward;
 
 
 
     if(flyer == 1){
 
        if(distanceToPlayer >= $$anonymous$$inDist) {
        if(distanceToPlayer <= $$anonymous$$axDist) {
          movement *= normalizedSpeed * forwardForce;
          movement += velocity;    
          movement *= Time.deltaTime;
          character.$$anonymous$$ove( movement );
        }
        }
 
        transform.LookAt(Player);
 
     }
 
     if(flyer == 0){
 
        if(distanceToPlayer >= $$anonymous$$inDist) {
        if(distanceToPlayer <= $$anonymous$$axDist) {
          movement *= normalizedSpeed * forwardForce;
          movement += velocity;    
          movement *= Time.deltaTime;
          movement.y = Player.position.y; // stay on ground
          character.$$anonymous$$ove( movement);
 
          transform.LookAt(Vector3(Player.position.x, transform.position.y, Player.position.z)); // no rotate up to lookat
        }
        }
     }
 
 
 }
 }
avatar image ArkaneX · Sep 07, 2013 at 08:57 AM 0
Share

Heh - I didn't know that comments under answer which is converted to comment disappear.

Anyway - repeating what I wrote previously, I don't see a framerate drop in my sample project. Unfortunately I don't know what is your project setup, so I can't mimic it. I set some random variables and objects in inspector though, and everything worked at over 60fps for over a $$anonymous$$ute.

avatar image ArkaneX · Sep 07, 2013 at 09:49 AM 0
Share

One more thought - have you probably uncommented some code in your Update method? If yes, then you're running more and more coroutines and this might affect performance.

avatar image
0

Answer by RyanZimmerman87 · Sep 07, 2013 at 09:12 AM

Do you ever set it to false? Or is it supposed to just infinitely move them.

I really think you should have some kind of control to ensure that their movements complete before you call them again.

I never used random. Value I always use Random.Range. But I'm guessing what's happening here is that Random.Range can roll very small numbers it's any float value between 0.0 and 1.0 correct?

Not sure if it can only be 0 OR 1 for the value like your conditions suggest but it seems strange to use a float for that if so.

So if you got .1 x .5 (your AI_Delay) that is .05 seconds. So you are potentially calling these moves to barely yield whatsoever and your frame rate is dropping because your processor cannot do all your AI movements before an additional yield timer is met and function called.

So you might start with just 1 yield function but I believe this number grows higher and higher and the higher. As it gets higher each movement will individually take longer cause so much other stuff is going on so it's a vicious cycle.

In short you need to ditch that while loop OR add a condition that only one movement can occur at a time.

Basically instead of having all this in inside a while loop you should just use StartCoroutine and Ienumerator. once the IEnumerator completes you call another StartCoroutine.

That would ensure that only 1 process can be going at a time where currently who knows what is going on that set up doesn't quite make sense.

For example:

 float randomNumber = Random.value * AI_DELAY;
 
 Start()
 {
 StartCoroutine (AI_Movements(randomNumber));
 }
 
 void restartFunction()
 {
 randomNumber = Random.value * AI_DELAY;
 
 StartCoroutine (AI_Movements(randomNumber));
 }
 
 IEnumerator AI_Movements(float randomNumber)
 {
 
 yield return new WaitForSeconds(randomNumber);
 
 //all your movement logic
 
 restartFunction()
 
 }

Apologies for C# that's all I use. But that example is how I would handle this kind of thing.

Comment
Add comment · 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

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

17 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

Related Questions

Coroutines randomly stop working 0 Answers

Best way to make melee AI damage player? 2 Answers

Enemy can only move in one direction at a time using transform.Translate and Coroutines? 1 Answer

FixedUpdate has stopped working 0 Answers

How can you tell if a gameobject is looking directly at another gameobject? 1 Answer


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