Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Enemy wont stop following me C#

Discussion in 'Scripting' started by zboy757, Apr 30, 2014.

  1. zboy757

    zboy757

    Joined:
    Apr 6, 2014
    Posts:
    12
    Hey guys. I watched a video and picked up a little bit on C# scripting. Testing this script it worked perfectly but the enemy wouldn't stop following me at a certain distance. I would like to know how to fix this so I can make my dream came work. (If you know how to add patrol into the script that would be cool too.) Hope you can Help!
     

    Attached Files:

  2. Suddoha

    Suddoha

    Joined:
    Nov 9, 2013
    Posts:
    2,824
    First a few fixes:
    - change CroassFadeQueued to CrossFadeQueued (twice)
    - you missed one curly bracket at the end
    - increase the speed in the transform.Translate function and multipy it by Time.deltaTime too as you've dont it with the rotation

    Your requests:
    - stop enemy from following:
    At the moment, you check if the player-enemy distance is less than 1, if it's not, you follow the player slowly. In oder to set a limit to distance that makes him stop following, write
    Code (csharp):
    1.  
    2. else if (_distanceFromPlayer <= 10)
    3.  
    instead of the simple else key word.

    Now, if you want the enemy to do something different that just standing where he stopped following you, you'll add your final else and the code for further movement. I.e. move him back to a certain position or something.

    As for the patrol, you could define an array of Vectors (or rather transforms or gameobjects in order to make it more dynamic) and always move the enemy to next position. That's a simple and basic solution, not the best though but enough for the beginning.
     
  3. zboy757

    zboy757

    Joined:
    Apr 6, 2014
    Posts:
    12
    Do I type a command like stopFollowing or what?
     
  4. Suddoha

    Suddoha

    Joined:
    Nov 9, 2013
    Posts:
    2,824
    No, there is no command like that if you haven't defined it anywhere as a function or whatsoever.
    Use the line i posted and replace the simple 'else' with it. This will make your enemy follow you as long as the distance is not greater than 10 world units.
     
  5. zboy757

    zboy757

    Joined:
    Apr 6, 2014
    Posts:
    12
    Thank you so much!