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 /
  • Help Room /
avatar image
0
Question by PaincideStudio · Feb 23, 2018 at 09:12 AM · yieldienumeratorboolchasewander

Coroutine never stops...


Hi.
I made two Coroutines.
One for wander and one for chase.
I used all kind of code to make wander stops when chasing, but it almost never chases player and wander.
I used yield break, yield return null, stopcoroutine, named it with string, etc...
But it never stops wandering..
I just let them yield break to see if it will make my wandering stops, but it doesn't!!
Here is my code.
Help me God bless you all.

     public Transform sight;
     public GameObject Player;
     NavMeshAgent navMeshAgent;
     NavMeshPath path;
     public float timeForNewPath;
     Vector3 target;
     bool inCoRoutine;
     bool chasing;
     
 
 
 
 
     void Start()
     {
         navMeshAgent = GetComponent<NavMeshAgent> ();
         path = new NavMeshPath ();
         chasing = false;
         navMeshAgent.speed = speedController.speedValue;
 
     }        
         
 
     void Update()
     {
                 // Two CoRoutines with chasing and wandering.
         if (!inCoRoutine && !chasing) 
         {
             StartCoroutine ("Wandering");
             StopCoroutine ("Chase");
         }
 
         if (chasing) 
         {
             StartCoroutine ("Chase");
             StopCoroutine ("Wandering");
         }
 
                 //This is for move animation.
         if (navMeshAgent.velocity.magnitude > 1.0f) 
         {
             anim.SetBool ("IsWalking", true);
         } 
         else
         {
             anim.SetBool ("IsWalking", false);
         }
 
     }
 
     Vector3 getNewRandomPosition()
     {
         float x = Random.Range (-45, -5);
         float y = Random.Range (-0.2f, 0.2f);
         float z = Random.Range (-33, 25);
 
         Vector3 pos = new Vector3 (x, y, z);
         return pos;
     }
 
     IEnumerator Wandering()
     {
         if (!chasing) 
         {
             inCoRoutine = true;
             yield return new WaitForSeconds (timeForNewPath);
             GetNewPath ();
             inCoRoutine = false;
 
         }
 
         if (chasing) 
         {
             yield break;
         }
 
     }
 
     IEnumerator Chase()
     {
         if (chasing) 
         {
             GetNewPath ();
             yield return new WaitForSeconds (timeForNewPath);
             target = Player.transform.position;
             navMeshAgent.SetDestination (target);
 
         }
 
         if (!chasing) 
         {
             yield break;
         }
 
     }
 
         
 
     void GetNewPath()
     {
         if (!chasing) 
         {
             target = getNewRandomPosition ();
             navMeshAgent.SetDestination (target);
         } 
         else if (chasing) 
         {
             target = Player.transform.position;
             navMeshAgent.SetDestination (target);
         }
     }
     
             
 
 
     void OnTriggerStay()
     {
         Ray ray = new Ray (sight.position, sight.forward);
         RaycastHit hit;
         if (Physics.Raycast (ray, out hit, 30.0f)) 
         {
             sight.LookAt (Player.transform.position);
             if (hit.transform.CompareTag ("Player")) 
             {
                 chasing = true;
                 Debug.Log ("Hello");
             } 
             else 
             {
                 chasing = false;
                 Debug.Log ("No");
             }
         }
     }
 
     void OnTriggerExit()
     {
         chasing = false;
     }
 
 }
 
Comment
Add comment · Show 1
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 PaincideStudio · Feb 23, 2018 at 09:38 AM 0
Share

You can just suggest me any solutions!

2 Replies

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

Answer by Hellium · Feb 23, 2018 at 03:45 PM

I know, the solution I propose is a total reworking of what you currently have, and it goes outside of the scope of your question.


I advise you to get rid of your coroutines which are difficult to handle in the Update function. Instead, manage your delay inside the Update function directly.


An additional improvement is to use the Strategy pattern to handle the states of your player. It will simplify your player class and you easily be able to create new states.


 public Transform sight;
 public GameObject Player;
 public float timeForNewPath;
 
 private NavMeshAgent navMeshAgent;
 private NavMeshPath path;
 private BehaviourState state; // 
 private int walkingHash ;
 
 void Start()
 {
     navMeshAgent = GetComponent<NavMeshAgent> ();
     navMeshAgent.speed = speedController.speedValue;
     path = new NavMeshPath ();
     walkingHash = Animator.StringToHash( "IsWalking" ) ; // Use this to optimize the call to SetBool
     
     state = new WanderState( navMeshAgent, timeForNewPath );
 }
 
 void Update()
 {
     state.Update(); // The NavMeshAgent will automatically retrieve the path at the specified interval
     anim.SetBool( walkingHash, navMeshAgent.velocity.magnitude > 1.0f );
 }
 
 void OnTriggerStay()
 {
     Ray ray = new Ray (sight.position, sight.forward);
     RaycastHit hit;
     if (Physics.Raycast (ray, out hit, 30.0f)) 
     {
         sight.LookAt (Player.transform.position);

         // If the player is in sight, activate the chase mode => create a new state which is updated in the Update function
         if (hit.transform.CompareTag ("Player")) 
         {
             if( !( state is ChaseState ) )
                 state = new ChaseState( navMeshAgent, timeForNewPath, hit.transform );
         } 
         // If not, activate the wander mode => create a new state which is updated in the Update function
         else if( !( state is WanderState ) )
         {
             state = new WanderState( navMeshAgent, timeForNewPath );
         }
     }
 }
 
 void OnTriggerExit()
 {
     if( !( state is WanderState ) )
     {
         state = new WanderState( navMeshAgent, timeForNewPath );
     }
 }


 public abstract class BehaviourState
 {
     protected NavMeshAgent navMeshAgent ;
     private float targetAcquisitionInterval;
     private float lastTargetAcquisitionTime ;
     
     public BehaviourState( NavMeshAgent agent, float interval )
     {
         navMeshAgent = agent ;
         targetAcquisitionInterval = interval;
     }
     
      public void Update()
      {
          //Debug.Log( Time.time + " " + lastTargetAcquisitionTime );
          if( Time.time > lastTargetAcquisitionTime + targetAcquisitionInterval )
              GoToTarget() ;
      }
  
  private void GoToTarget()
  {
      navMeshAgent.SetDestination ( GetTargetPosition() );
      lastTargetAcquisitionTime = Time.time ; 
  }
     protected abstract Vector3 GetTargetPosition(); 
 }


 public class WanderState : BehaviourState
 {    
     public WanderState( NavMeshAgent agent, float interval ) : base ( agent, interval )
     {
          GoToTarget() ;
     }

     protected override Vector3 GetTargetPosition()
     {
         float x = Random.Range (-45, -5);
         float y = Random.Range (-0.2f, 0.2f);
         float z = Random.Range (-33, 25);
 
         Vector3 pos = new Vector3 (x, y, z);
         return pos;
     }
 }


 public class ChaseState : BehaviourState
 {
     private Transform target ;
     
     public ChaseState( NavMeshAgent agent, float interval, Transform t ) : base( agent, interval )
     {
          target = t ;
          GoToTarget() ;
     }
     
     protected override Vector3 GetTargetPosition()
     {
         return target.position ;
     }
 }






Comment
Add comment · Show 28 · 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 PaincideStudio · Feb 24, 2018 at 07:25 AM 0
Share


Hey!
Should I erase all the using System things?
Cause I can't see nav$$anonymous$$eshAgent without .AI in BehaviourState.

avatar image Hellium · Feb 24, 2018 at 11:29 AM 0
Share

@PaincideStudio : I've erased your last comment by mistake....

Hey everything works fine But he keeps confused to chase my Player when he raycasts my Player. He wanders fine, but he confused to chase my Player.. I think I need to fix the chase state.

What do you mean by "he confused to chase my Player"?

avatar image PaincideStudio Hellium · Feb 24, 2018 at 11:38 AM 0
Share


He goes to my player about one step and goes back to wander one step and again goes to my player one step and he loop this forever..


if( Time.time > lastTargetAcquisitionTime + interval )


Also In that script, if I put interval,the name 'interval' does not exist in the current context pops up. If I put targetAcquisitionInterval it doesn't make error.

avatar image Hellium PaincideStudio · Feb 24, 2018 at 12:54 PM 0
Share

I finally took the time to test my code. I fixed my answer. It should work now.

Show more comments
avatar image
0

Answer by PaincideStudio · Feb 25, 2018 at 11:11 AM

I re-exported my model and it worked. Thx for helping me out!

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

132 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 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 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 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 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 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 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 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

Could not load source 'Coroutines.cs': No source available. 1 Answer

wait WWW to finish download with yield does not work 0 Answers

How to skip WaitForSeconds? 1 Answer

IEnumerator skips remaining function after yield 1 Answer

Unity - Lines after yield not getting executed 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