Unity AI Patrol, Chase, Attack Tutorial in Less than 8 Minutes(Advanced AI Controller)
HTML-код
- Опубликовано: 19 июн 2024
- In this tutorial I'll show how you can make an advanced AI controller, making your enemy patrol, chase and attack! SUBSCRIBE for more tutorials :)
Join the Patreon for special access →→ / danncs
Join the discord server →→ / discord
Script: pastebin.com/WGWfA705
Instagram: / officialdancs
Facebook: / dancs-101265175484128
Music: / @freemusicc
Chapters:
0:00 Intro
0:19 Start!
1:05 The Script!!
5:35 Finished Script!
6:10 How does it look??
About me
Hey! I'm an indie game developer, currently working on a mobile survival game in Unity. This is my devlog where I show off the progress and I'll upload once a week! Наука
I was not able to find this thing anywhere from last like 4 hours, but just gave a simple yet the best tut out here
Things u forgot to mention. Adding waypoints ( just use empty object and place where u want, if u r getting out of bound error).
Baking, before backing go to right tab, object, select Navigation static, now bake will work.
how would you make the enemy ignore you if you are behind it?
you are the man, thanks a lot!
@@youme2460 Just adjust the angle.
you're a fucking god, thank you
do u have to do anything to the empty gameobject or just place it down where u want it?
Thanks you so much, after a few hours of making mistakes I finally made it work!
I have been looking for a long time on a good tutorial and im happy to say that I finally found one.Really easy to follow and upgrade with my own code. THANK YOU!
Great tutorial man! Thank you!
Thank you so much for this awsome tutorial!!
Great tutorial!! Thank you so much!!
Thank you so much bro, it helped me a lot. I can build on this code to make my own monster enemy in my horror game. Thanks :D
I got you for that 50th subscriber! :3 Thanks for the super easy to follow tutorial and i'll be using this into my game!
Thank you
hi i made everything its almost work fine but agent doeasnt go to the patrol points and when ı got out his range it says "object reference not set to an instance of an object" how to fix it did everything right
To make more pro like you should split the parts like component based design works.
Patroling, Playerfinder, MovementScript. The player finder can use unityevents like if you find target disable patrol Script if you lose target enable again. Patrol script would send next position to movement script and playerfinder as well.
There are loads of tutorials like this - AI cylinders moving around the place. What nobody seems to do is use an animated avatar and show how to use blend trees to control movement and speed for patrolling, chasing and attacking. Anyone know of this I would be grateful.
Did you find something ?
just add a public animator component in the script and add few bools to the enemy like , walk , chase , attack etc.... and use animator.setbool function in the states of walk,attack and chase. then it will work
Hi. Thanks for the tutorial. That is very helpfull. The "CaughtPlayer()" methode is never used. Is that right ?
You earned it with this one! +1 sub.
keep ur good work brother luv
I have 2 issues, the enemy moves through my obstacles when it patrols but once it starts following me it starts having collision with them, also once it follows me and i break line of sight it never goes back to patroling, any suggestions?
I'm getting very confused on 5:35
I made the layers but have no idea what to do. My enemy capsule is just rolling around like a normal rigid body. For my player I used unitys first person template and renamed the player capsule to Player. I know I've done something wrong or missed something important.
Doesnt work, I did everything the video told me and the enemy doesnt move. You probably shouldn't speed through teaching AI since its a complex thing.
um, when i get out of sight for the ai and it's supposed to go patroll from the first waypoint it just walks in place(i added an animation) and doesn't go to the waypoint until it sees me agaun. please help
If anyone is having problems with the enemy colliding with the player & it's causing it to drift off by itself. Then you need to set the enemy rigidbody to kinematic 👍
Alternatively, if you don't want your enemy kinematic all the time, add this to your chasing state:
(First add a reference to your enemy rigidbody)
If(vector3.distance(transform.position, gameobject.findgameobjectwithtag("player").transform.position)
That will work here. One thing you will eventually want to learn to do is setup the collision layer masks so that certain objects don't collide with your player. The same principles are used in 2d layer collisions like in this tutorial: ruclips.net/video/aTnNje9j3o4/видео.html
i think you can also just constrict the position n rotation, its much better
Hey man, everything worked but the enemy is not going back to the patrol waypoints after seeing the player, am i missing something?
do you have problems with EnemyAI triggering NavMesh.SetDestination lagging or freezing the game for a few seconds? I do
Hey Dan,
I have been able to implement your code into my game but I am noticing there is no actual attack code within it. Would you be able to create a short video how to add attack code to the script so my enemy ai is able to attack in melee range? Thanks again for the quick and clear video, you definitely earned a sub!
There is a video on my channel called how to make combo attack which connects to this
Ahh understood have to add the elements to the wayPoints
What if i wanted to add a value called isHidden and when the AI is chasing the player and the isHidden value inside the player turns true the AI suddenly goes back to patrolling ?
Can i use this method to unity standard asset third person character?
I almost always have an enemy stuck in a corner and run in place if the player turns around the corner during the chase. He does this until he walks back or walks out of the corner. What to do?
Make the capsule collider smaller
I'm confused about when (m_playerNear) is true. its set to false on start function so when is it actually set to true.
I had some trouble applying the BAKE because he never said to set the cube to static in the navigation object menu.
for those who had the same problem: select the ground (or tile) >Navigation > Object > Navigation Static [V] > Navigation Area [Walkable] > Bake > {Bake button}
how do i implement for enemies to stop at certain distance from player and start shooting projectiles. Thanks for the really good tutorial though
sorry to both but if you found anything that answered this question, please send it my way
Hopefully you see this! I love the script but my one issue is that my obstacles all disappear in game view and i can not understand why, if you could help that would be awesome!
Hey, I dropped a message in your discord. Unfortunately I've been having some issues with getting this working. It looks like the GetComponent for the NavMesh is being reset each time. Not sure if this is due to an update in how Unity operates now
I create this tutorial, but agent go in 1 point in 4, and not deteched player, why this maybe? My player use character controller, this can be because my player haven't rigidbody?
I keep on getting errors saying “expected” or “invalid term ‘’” and “Type or namespace definition, or end of life expected” how do I fix this?
How do you add animation the script or in turn just drop a script for US to access it you can as well tell us here
do you have the full version of tutorial i didnt follow some steps like im lost
The people who are using this Don't forget to give a tag "Player" to your player controller and Great video!
I tried this but for some reason the AI will still follow the Waypoints and ignore me :((
This is a great tutorial! Although I am implementing this into my 2D game, and am having some trouble modifying the script so that it works within Unity's 2D NavMesh. Does anyone have any suggestions at how to modify this script for a 2D game in Unity? I have already tried substituting all of the Vector3's to Vector2's in the script and that doesn't seem to work. Thank you!
I have problem, every time I get out of the enemys "chase" stage, the game stops and says "object refrence was not set to an instance of an object.
guess the enemy gets mad when he cant see me
Is there any way to make clone of enemy ? With singal AI script, also hit sound damage sound and AI sounds
Good tutorial. But what if you play with friends and everybody are in AI view?
can anyone explain where i put the AIControler script at? im using it to Enemy but seems like i make a mistake at it, so maybe can anyone tell me how to use it, please?
how is created the array? I've never delt with it before so now i'm a little lost, i tried Unity documents but they don't teach about this
They do: docs.unity3d.com/2020.1/Documentation/ScriptReference/Array.html
yay im the 200th subscriber
Thankss!!
Hey this is my first time making a game so I am a beginner at making games right now. I have downloaded the script and want to ask a question how/where should I edit the code to where when the enemy AI touches the player a event happens like game ends, game over, or something tells me that such event happen.
Please and Thank you.
You would do that on the on trigger event, or the on collision event. These two are simillar but not the same. You can check unity docs for things like that. Don’t be afraid to google everything, and also watch youtube videos where people explain to you the basics like controlling the inspector, or doing small things like that. There are good beginner tutorials on unity so make sure you familliarize yourself with tags, gameobjects, rigidbodies so you know how the engine works.
@@DanCSS Thank you for replying man, appreciated it.
so im having a problem, I copy and pasted the script but it says "Index was outside the bounds of the array" any idea what this means?
(its on line 50 and line 121)
you might have to add waypoints
is there any way that i can loop the patrol?, mine is not looping
Nice video! My only question is that if I could somehow add the CaughtPlayer() function to the script like, if the enemy is close to the player then call the CaughPlayer function, thanks!
Hi, sorry, probably late answer. I am still new into coding, just had an idea to maybe do it through collider? So when enemy enters collider (around player), then freeze all movement for player and enemy? But that's probably really basic, you want something more complex I guess.
Thanks for the idea but the player wouldn’t be able to go close to things, I already solved the problem, what I did was change the “Stop Distance” (I think thts what it’s called) to 20 so he stops 20 units away from the player, you can set this number to whatever you want and he will stop at that distance
Thank you for answering! :)
@@retrovoorhees8160 No problem, glad you figured it out. :)
@@retrovoorhees8160 can you please mention in code where did you changed
do you know why its out of bound? i dont know how to adding waypoit
Can you please make a tutorial on how to make it animated please
great tutorial, but what do i have to put on the waypoints array?
I have the same problem.
@@lehmus4308 Anything you want, a gameobject, gizmo, prefab..
so how to do a function where when u are caught something will be triggered?
What are the models you are using ?
You can find models on mixamo, I made a video on mixamo a while back so you can check it out aswell
how do i make the terrain walkable in 2d orthographic view
If it's not working for you. He got a some of it incorrect. Some void updates are private. Check the copy-pasted version.
There should be a:
m_Player is near:
on line 40
:/
How to fix IndexOutOfRangeException: Index was outside the bounds of the array Error..Please help me :(
How can i fix that the enemy goes back to Patrolling after he loses me
Isn't there an error at 3:58 that you never fix?
Ikr
Not sure what's happening but it seems the enemy works as intended until after he's spotted me and I get a certain distance away from him. Game just crashes at that point
you got to give the player a player tag
Can i get some help getting this ai to work it wont go to the way points or chase the player it is literally driving me mad
instead of the enemy going to me, it goes to the waypoints, and completely goes around me. does anyone have a solution?
I'm looking for videos that have the enemy ai animation snapping back when it loops i can't fix this no one is talking about it 😐
My AI just go to the first checkpoint and don't go to the next one, it just go back and forth in the same checkpoint. I copy pasted the script.
Anyone knows how to fix it?
please help me, i used your code, its running but i got a error it says "index out of range exception unity", what should i do?
fixed it yet? if you didnt, the solution is to add empty game objects as waypoints, put them around in your floor, and go to the script inside the enemy, on the bottom of the script tag, there should be "Waypoints" open it, add a few, and implement the empty game objects into the things
my character stops at the first point, I did everything as shown in the video. Has anyone had a similar problem?
Same.
can you make a guide on how to add animation with this AI Script
i know this is old video but does anyone know how to fix error m_Ispatrol does not exist lines 187,21
Hey for some reason I am getting an error that the index is outside the bounds of the array for waypoints
You need to put in transforms in your Waypoints array
@@priestartor9065 Sorry to bother but can you specify how to add transforms? I don't understand the syntax. I keep trying to set Transform[] equal to an empty game object but that obviously doesn't work.
@@yackasone I think you should have the transforms array public then in the inspector drag in the GameObjects that you use for waypoints. Hope that helps
So I got it 'mostly' working. After I added some waypoint gameobjects to the waypoint array (which I think was missed in the video?), the guard would walk to the first one, but not the second one. Is anyone else having this issue as well?
I did note a script below making sure that the nextpoint loops back to the first one, but this doesn't seem to be the problem in regards to getting to the second waypoint...
I got the same issue. Enemy will go to the 1st waypoint in the list and just stand there.
Yeah mee to, how did you fix it
@@techorigin5850 Was months ago so I forget sorry, can't even remember if I did manage to fix it!
What does IndexOutOfRangeException: Index was outside the bounds of the array. aiController.Patrolling() mean?
Hey Ive been having the same issue. I was just wondering if you ever found out what the problem was.
@@villocity5794 u have to assign patrol points.Empty gameobjects into waypoints in editor. Array is empty thats why u get this error
"Couple of bools...."
it gives me this error Index Out Of Range and my enemy model is getting gone
how do i fix out of bounds of the array error
I got a error because of the waypoints. It says IndexOutOfRangeExpection: Index was outside the bounds of the array. Can anyone help
Add object anywhere
Set the objects as waypoint in ai script
how to I change the radius of the AI. Like if I want the AI to stop within like 1.5 radius of the player so it's not pushing the player trying to get to the center of the transform?
edit: I fixed it with adding this...
if (Vector3.Distance (enemy.transform.position, player.transform.position) < radiusofNearPlayer)
{
CaughtPlayer();
}
else if(Vector3.Distance (enemy.transform.position, player.transform.position) >= radiusofNearPlayer)
{
playerLeftRadius();
}
,but the AI takes about 2 - 3 seconds to slow down even inside the radius of the player. The radiusofNearPlayer us just a public float so I can change values in the inspector. Any help would be great!
You can change the stopping distance on the nav mesh agent in the enemy inspector
@@DanCSS wow just saw your comment lol after I came up the a different method that still took a while to register in the area like to slow down. Anyway, thanks for your help! There is one last issue... If my player hits him with my hands (I am in VR) (just a mesh with a rigidbody and mesh collider) the AI will then keep going forever in the direction I hit the AI and won't stop and start moving again. How do I solve this? Thanks, also just subbed!
@@tacticalmythic7945 you can maybe put an animation after the enemy gets hit, or maybe make some sort of cooldown. I think I googled how to do a simple cooldown when I did my project. Maybe make a method that detects if the enemy has been hit, put a cooldown and then continue.
thanks. I found my own method. Now I am stuck where the player is moving away and the enemy is still attacking while moving. using nav mesh. Basically it attacks when the player is at the stopping distance (when its still). I then have the player move, but the animation attacking is still playing and moving. Instead of waiting for the animation to finish, then start movin again.
If anyone else is struggling with this, alternatively you can make the enemy kinematic when it gets close to the player to avoid the collision causing it to glitch out
Here s one sub
Does anyone have an idea about the waypoints ? Do I need to manually add them ?
It doesn't work how many times I try. It gives index error.
Does this work for 2D?
how to set waypoints loop ?
My AI sees me through my back!
Does anyone else have the problem of the AI shaking once it touches an object with the layers "Obstacle" or "Player"? For me it just shakes and stands there without returning to the waypoint.
Wondering if anyone has a fix for this, thanks!
Rigidbody -> is Kinematic -> True
where tf did you find the AI in window?
on pastebin code is missing!
I copy and pasted my code in, and everything was working fine, but there was always an error saying that the index out of bounds of the array. Also my 3d model that I had attached the AI too wasn't following or moving or anything. I followed the tutorial exactly, with doing the baking and everything, and the model will move, but only if I push it with my character. It won't follow me or patrol.
Are you sure that you copied the inspector that I have?
@@DanCSS I wasn't baking/static the floor correctly. I have multiple platforms to form the shape of my floor, so I needed to bake them all. It is fixed, and the code works perfectly! The only thing is that the index error still pops up, though it doesn't affect the code. Also unity is being buggy and my POV controls froze, but I just restarted. In general, is there a reason certain aspects of your game will stop working when others are put in?
@@DanCSS Also I subbed, because your content is great!
@@037productions thank you man, that really means a lot!
@@037productions Sometimes Unity just needs a restart. There is sometimes bugs in the console but you can play and everything works out, so a restart once in a while does help.
can you show us a script of the animations please?
I will try to make that video soon since a lot of people are interested in it.
my ai keeps turning to face the floor instead of being upright
I tried but it was too hard and it wouldn’t work
IndexOutOfRangeException: Index was outside the bounds of the array.
same
@@sillioskari2109 You need to put in transforms in your Waypoints array
I got an error. "The name "player" does not exist in the current context." It's in Void Environment View. The guy making it got an error, but it doesn't show us him fixing it!
Edit: I found the script in the description and it works.
you see the } above it move it below the if statement
@@VIKHR9x39 Edit: I found out earlier that he made a pastebin script which fixed the error.
make a video on how to setup the animations pls
I made that video previously on my channel, you can check it out.
I would like to see character mouse look script and walking.
Are you Serbian, saw that ž slipup while writing :D
Do you know who's Joe?
What about attacking
Pleease help,how do you add navmesh to unity i down fucking understand.
Can I use this commerically? I also subbed to ur channel ;)
You can
@@DanCSS THANK YOU SO MUCH!!!
how animations?
Check out the discord in the description, it should be there. Or checkout my video I did before.
Why isnt there NavMeshAgent on my screen?
You have to add it as a component
Hi, instead of chasing me, the enemy runs away from me?! please help
Make sure you got all of the code copied correctly
@@DanCSS i did, i copied it from your website. And it didnt show any errors. Di you do something in the video that wasnt in the code to copy
@@xrono6003 I didn't, but if you have problems you can download the entire script on the discord. Maybe that will help.
The enemy justo don't follow and pattrol, and i copy exactly the code of the video