ADVANCED AI IN UNITY (Made EASY) - STATE MACHINE BEHAVIORS
Vložit
- čas přidán 7. 09. 2024
- In this AI unity / C# tutorial we will take a look at how to use the animator to get your enemy characters or NPCS switch behaviors, movement patterns, play sounds and more !
------------------------------------------------------------------------------------------------------
LINK to the ANIMATOR TUTORIAL : • HOW TO MAKE ANIMATION ...
LINK to the ENTIRE AI SERIES : • AI TUTORIALS WITH UNIT...
DOWNLOAD the PROJECT : github.com/Bla...
------------------------------------------------------------------------------------------------------
SUPPORT ME : / blackthornprod
------------------------------------------------------------------------------------------------------
FOLLOW ME on TWITTER : / noacalice
JOIN the BTP DISCORD SERVER : / discord
Damn. You can make an entire game inside of the animator. That's crazy.
It feels like whenever I need to know how to do something for my game, you just happen to cover it! Great video!
Yes, Noa is Amazing
How did I not know about behaviors in the animator?
Same, I’m mind blown!
@@AOG91 DITTO
same here!
Yes
Yes
Yes
So much easier than using the official unity video (Finite state machines probably outdated)
Most useful video yet!!!
everything on the unity site is outdated some as old as version 2
This video was so helpful but not in the way you might think. I know how to make advanced AI using a finite state machine, But I've completely overlooked the StateMachineBehavior with the Animator to play particle effects or other behaviors when entering and existing animations! THank you!
WOOOOW...
I tried myself to make a state machine countless times and in the animator is one just waiting for us!!!
Noa you are great and you save me a lot of time :DDDDD
I expected part 2 of ranged attack tutorial first, but this is a great Video. Loved it !!!
Thanks :) ! I'm really happy you liked this video, and of course ranged combat Part 2 will come out soon enough :) !
Awesome and unique tutorial. This tutorial really opened my eyes about the possibilities Unity is offering to develop quality games. Great thanks for these kind of tutorials.
Of all the people out there making tutorials for UNITY your videos are definitely the only ones that say "go watch another video to learn this part".
Most people show how to do something from start to finish. Not show the middle and then recommend in their video to go watch two other videos. click bait is click bait
so we can add scripts to an animation! wow....
Most enemies in the game Rainworld uses animator behaviours for AI
@@MrPoporucha cool!
What's also awesome is you can add scripts to the animation itself.
You open the animation window, drag in the animation and then you can add a script anywhere in the time of the animation.
So you can start a gun particle or hammer swing at any point in the animation.
Like if your enemy has a delayed jump, then instead of coding in a delayed particle, you instead just make the animation call the function in the script at the point he jumps.
Easy peasy lemon squeezy
@@magnusm4 nioce
You have blown my mind, the animator behaviors are brilliant!
WHY CAN'T I THUMBS UP MORE THAN ONCE!!! Haha, great video. Very informative, simple, and useful information.
Blackthornprod: some vicious warcry
No one:
Enemy: yAAAA
With full sincerity, thank you so much for this video and doing what you do. This answered so many riddles I had about hurdles with my own game and propelled my knowlegde / progress forward so much I cant even tell you. I swear I was just waiting to find this video. Cant thank you enough.
Wow I never knew how to utilize the behavior scripts. This is drastically going to change the way I make CCs and AI
Could you make a tutoriel about smart enemy ai (can jump, climb,...) on side scroller 2D?
1ht1baron that would be different you need to be on the intermediate tutorials mate
@@Zakiev_Omar LOL
Amazing and simple tutorial, this will boost my production really well!!
Awesome this just give alot of ideas on how to make my ai with ease
I'm using animation events all the time without knowing that I can attach script to animator states...
Completely revolutionized the way I'll do AI from now on!! :)
Great tutorial but please if you can do a tutorial on tilemaps because I'm sure that it will be great to learn that from you
Easily the best tutorial of this type on CZcams
Hey Noa! Great video and your Ludum Dare game looked so fun! I hope you were able to get your game on the leaderboard! Is this what our boss battle tutorial is? If so it’s made very well! Have a good morning, day, and evening!
Thanks Ben :) ! No this wasn't really my boss tutorial, that will come out some time soon ;) !! And I'm really glad you liked my LD game ! The feedback I received was awesome, helpful and so motivating (3rd most rated game of LD so far :D) !
Blackthornprod well I hope it stays in that place or goes up
once again another awesome tutorial from my fav unity channel
best State Machine explanation video ever.
Alright next tutorial has to cover ai moving around obstacles
@@ILPYou what about in 2D
@@JaycubMacawl dont make 2D
Awesome tutorial as always!
Thanks for the great tutorial! Loved the simplicity of this technique. Without animations, I encountered a 0.5s delay between exiting state A and entering state B. -> The "Has Exit Time" has to be turned off for fast transitions.
Alright, where's the promised part 2? :D
unable to use the search function???? czcams.com/video/bY4Hr2x05p8/video.html
@@TheUnscriptedMind thanks but that link is to a 2D ranged combat system
@@Norbingel and he said what? Part 2 "Ranged Combat Tutorial" .... 7:45
@@TheUnscriptedMind I was actually referring to 7:30 where he said "it is very likely that I made a part 2 State Machine Behavior Tutorial in the near future" right before he says the part about making a Ranged Combat Tutorial.
@@Norbingel czcams.com/video/cXefXSD2SM0/video.html maybe this? that video was 1 week later and has state machine behaviours...
"Ahhhh, help! The enemy is FARTING towards me"
Finite State Machines are also good for controlling the state of the game, i.e. MainMenu, Running, Paused, Game Over, etc.
I also ended up writing my own generic FSM for my LD42 Compo entry, but only used it for the game state. If I make enemies it's generic enough to use for enemies behaviors.
I've never used the animation system to control states though, that's a neat way of going about it.
This is how a state machine works???? This looks very understandable
Never used state machines before, but it looks really nice to use, gonna try it out for sure :)
I know that my comment is late but if you want to check if the player is near the enemie you can
Physics2D.OverLapCircle(enemie.position, raidus, "the layer of the player");
Damn, this is a more easy to understand than my current enemy AI script. Thanks!
Yup you opened my Eyes. Starting Unity now....
I have made game in Blender Game Engine in the past and I gotta say im glad ive started learning unity.
next step is the Unreal Engine, 100 times more powerful than Unity :)
@@leetness13what you're saying is bullshit, unity and unreal engine are both same powerful
today i learnt a new thing. i have never seen this type of tutorial before......thankssss.......
i want to confirm one thing that does 'animator.transform.position' indicates enemy position in this tutorial?
now i am waiting for part-2 of this tutorial.
great work.....
Yes, animator.transform.position does indicate the enemy's position because we are setting it to move towards the player.
"animator" is a property in the StateMachineBehaviour class of which the script is deriving from, which has the type Animator and holds a reference to the Animator component on the GameObject, in which holds the property "transform" of type Transform, which holds the reference to the GameObject's Transform component, in which has the property "position" of type Vector3, which holds the position of the GameObject.
And since the Animator he was making a behavior script for was sitting on the enemy, yes, it is referring to the enemy's position.
@@user-bo5vr1ib6i thanks
Cheers for the videos mate :) You always have really top notch stuff.
AI with pathfinding for 2D would be great as well. Something like A*, but with your breakdowns of the mechanics would be very helpful.
I second that
Hey Noa thanks for the video, I absolutely love your content, can you please recommend some learning materials for Unity??
Hey :) !! Best learning material available is on the actual Unity website (Space Shooter and Top down Shooter series) and on CZcams (on my channel, Brackeys and Sebastian Lague ;D) ! You can also check out the UDEMY website and search for Unity courses, there's a couple great tutorial series out there as well (payed though)!
Thanks for replying, keep up the great work!
Sebastian Lague tutorials are really good if you're from a programming background, you'll find his videos interesting.
Thanks for the tutorial! This is really useful for my current project!
Great video! I remember watching this when I was new to game development and now that I'm more experienced I was wondering when you would want to use this rather than regular code?
Dude, you deserve lot of subs after brakeys leave you are been my brakeys now
Great video, can you explain how to do the same thing but rather than hitting a button to change states, the npc changes states with either line of sight or within a range of the npc
We have used that same system to create some Boss AI in our student game ^^
A Better AI option is behaviour tree if you need very complexe AI !
Are there any downsides to using the animator's state machine as the AI state machine? And on the flip side, are there any upsides to creating a parallel, code-based state machine for the AI and keep the animator state machine to visuals/animations only?
Really want the answer to this! Stumbled across this video because i'm lost but i'm not sure if it's good practice to use it without any animations..
When do you use State Machine Behaviours and when do you create your own pure C# State?
Finally, waiting so long!
Hey Noa, i need a bit of help.
do you know where I can find some tutorials for Unity on making a cooking tycoon?
I been trying to find a cooking tutorial where the player has to cook, then leave there cooking station to sever customers. Kind of like Chocolate tycoon but instead of the serving the customers at the counter you serve them at a table.
If you don't know any tutorials on this could you please post a video explaining how you would tackle the challenge.
God... That was easy... Thank you so much Noa
Very cool! One question: is this state machine animator a separate animator from the enemys walking animator?
instead of key down to get him to start following from idle i just want him to start i dont want to press keys.. how would i do this?
This is interesting, but wouldn’t it just be easier to give them multiple scripts and use setActive when you want them active, and the opposite when you don’t want them active?
cool use of the built in state machine :D
Love your tutorials! Thanks
Why you cant drag and drop gameobjects from your SCENE onto public GameObject in your scripts that were added to particular animation? Normally thats obvious that it works, in normal scripts it always works, but if scripts is added thorough this add behavior options, this just doesn't work...
Thanks for the video !
Is that really a good approach to controll AI through anim states? shouldnt some ai manager itelf controll animator?
Yea, a very interesting question. Cause... it looks strange when AI is controlled by ANIMATOR, not vice versa
@@caxopog stranger things ... ;-)
It's actually alright. It's good for visualization
@@tonywoods1226 I think the point is for any project of decent size, you probably want to isolate your "animation layer" from your "AI state machine layer" better than this. It's a good visual tool, but it's not how you probably "should" code it, separate from Unity's helpers. It depends a bit on how much of your game BL code you want to live "in" Unity, vs just being C#.
EDIT: since this has a few updoots now, and as someone doing exactly this, I'd say (in general) aim to have your new state's "onBegin" callback trigger your animation changes. That's worked really well for me so far. "Player hit attack button -> change to attack state -> animate the attack", with various BL/validation goo.
wondering myself. There is a Unity talk with the Fire Watch developer talking on state machines / animator. And at the end he is warning on using the animator as a state machine, like shown here as well. He meant it can get easily very complex and hard to debug, if everything lives in the animator. IMO, It's definitely no issue with a simple project like shown here, but rarely any tutorial shows an implementation for an actual realistic project, with more than just two objects following each other. I'm tempted on using it, but I think down the road, I will be making my life easier when the Finite-State-Machine is controlling everything incl. the animator, and not the other way around. Jason Weismann is showing good beginner friendly implementation of FSM, if anyone is interested.
Been stuck on movement controls for years.
But this state code has gotten me so excited I immediately got to Blender and started modeling to then rig and animate it to use this.
Is it possible to have already declared variables? So for example you don't have to declare a movement variable to be equals to the player's velocity every time you start walking . Especially if you have multiple variables and stats affecting movement.
I wonder if these state scripts can get other scripts's variables.
For example I still have a movement script on the player which handles falling, input, physics, drag and such so that there's universal effects on the player regardless of animation state.
Also accessing some variables of the player such as speed, strength force etc.
Wouldn't want a Tomb Raider where jumping is hard coded so you can glitch and run in the air. Still have no idea why anyone ever thought that was a good idea.
Another awesome video. Thank god for BTP :-)
With the MoveTowards the enemy can't collide with any colliders. Is there a way to prevent this?
The "private PatrolSpots patrol;" is highlighted with red... what i need to do? I need to create a script called PatrolSpots? If i need to do this what needs to be writhed inside this script?pls help;)))
Late reply but you’re going to need another script called ‘PatrolSpots’. I’m sure this is all explained in his AI series, but it looks like the PatrolSpots class will probably generate an array of random coordinates Called patrolPoints. Basically you’re gonna need to watch his other series on AI.
I was wondering about this too. I looked at the project files and PatrolSpots and the only thing inside of it is an array of transforms called patrol points. Not working for me. But here's the link to the script github.com/BlackthornProd/State-Machine-Behavior-Tutorial/blob/master/State%20Machine%20Project%20Files/Assets/Scripts/PatrolSpots.cs
You are the best youtuber for the unity tutorial
Thanks so much for the encouraging comment :) !!
You just saved me from a spaghetti code...
it definitely opened my eyes!!
Hey Noa, I've come across your channel recently and you've pretty great content. Can you make a video specifically for game audio as in how to select audio or the theme to the game and its implementation.
Awesome! Could you do a tutorial on how to integrate things like opening doors into AI pathfinding?
make a sight collision box and if there is a door close in the sight collision box, open it. (the script is really simple, nothing special.)
@@tijon1350 hmmmm is it though? What if he's in a tight space and the collision box hits 2 doors? I've been having a lot of trouble with this tbh, I was using raycast earlier but haven't touched the idea in a while.
cool. this exactly what i am looking for. thx
highly unlikely this gets a reply now, but no matter what i try i keep getting null reference exception errors for the patrol behaviour when trying to make it work from the other video, anyone able to help?
part 2 pleasee! nice vid keep it up !!
Very useful tutorial.
awesome video dude .. ❣❤
How would I flip the sprite in the direction it is moving?
Do You Know How To Make A More Advanced AI
So Like Level
3 AI
hi noa, can you make a tutorial about how you make (walking/running/idle/jump) animation ? cause i am having a hard time with it.
Il send you a link later if i forget remind me
@@dc5285 i think he forgot to remind you
thank you bro
Hi there blackthorn. Love you video very much! Can you do a tutorial on how to make a 2D character slide for dodging obstacles? Thank you so much :)
Nice video!!, can you make a full RPG tutorial?
really great job !!
All the spaggetti code to the trash. Must remake the AI again. I love you man....
I'm crying... kinda happy?
Question, is this better than coding state machines with enum and switch cases?
i have a problem with the patrolspots thinggy
andd pls correct my input
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PatrolBehaviour : StateMachineBehaviour
{
private PatrolSpots patrol;
public float speed;
private int randomSpot;
override public void OnStateEnter(Animator animator, AnimatorStateInfo stateinfo, int layerIndex)
{
Patrol = GameObject.FindGameObjectWithTag("PatrolSpots").GetComponent();
randomSpot = Random.Range(0, Patrol.patrolPoints.Length);
}
override public void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
if (Vector2.Distance(animator.transform.position, Patrol.patrolPoints[randomSpot].position) > 0.2f)
{
animator.transform.position = Vector2.MoveTowards(animator.transform.position, Patrol.patrolPoints[randomSpot].position, speed * Time.deltaTime);
}
else
{
randomSpot = Random.Range(0, Patrol.patrolPoints.Length);
}
if (Input.GetKeyDown(KeyCode.Space))
{
animator.SetBool("isPatrolling", false);
}
if (Input.GetKeyDown(KeyCode.P))
{
animator.SetBool("isPatrolling", true);
}
}
override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
}
}
Does this no longer work? I'm having issues with the following: transform. It says, "GameObject[] does not contain a definition for 'transform' and no accessible extention method 'transform' accespting a first argument of type 'GameObject[]' could not be found."
override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
playerPosition = GameObject.FindGameObjectsWithTag("Player").transform;
}
Russell Zeeryp Did you named “playerPosition” on your Transform field? Did the player gameobject have the tag assigned correctly with “Player”?
I just learned how to make state machines, I've been doing it by hand all in code and just learned that this exists... ugh
The type or namespace PatrolSpots could not be found...
just wondering, what's the difference between if we add the same scripts to the enemy and to the animation?
If i want to make the enemy from follow to idle it should be vice versa right? Which mean that the enemy will chase me and then when i press button it will stop. I'm fairly new to unity, so i'm so confused rn.
Great video. Thanks a lot :)
amazing good work. ! Keep doi'n it.
can u please do a video which covers the dimensions, optimization and quality of art in pixels (should sprites be in 1024x1024 , 512x512 etc or ) for better and maximum result in unity without having any performance issues
Kind Regards
abdul
Is it possible to have a main script that the animation scripts either inherit or gets their info from?
For example I have a player movement script with a Character Controller and a mainMove Vector3.
I want the animation for jumping to make mainMove.y = jumpHeight;
So basically, instead of coding all the movement stuff in a movement script I spread each action to the animations and the main movement script instead handle input and setting variables as well as holding them.
So the animation scripts don't instance mainMove but reference it so they affect the main movement Vector3
Is there a way to change npc animations as regards left or right direction? I've tried using blend trees, but i can't make it work.
My eyes are now open. And my mind blowed up
Thats gunna be an insta-subscribe from me dawg.
Cool tutorial
I was wondering: isn't it costly to initialize the fields of the behaviour every time OnStateEnter is called? Is there a better way to initialize things once, like patrolSpots?
yeah especially with using findGameobjectwithTag, better to cache it. something simple I can think right now is put a bool check condition to make sure the patrolSpots is found only once
What the freak, didn't even know there was a thing like this that existed. And now when I think of it, yes there was this add behaviour button on animation states, and to my surprise I never bothered to care about what it actually does 😅
Best unity youtuber!
Thanks so much mate :) !
I used "Rigidbody2D" here and it doesn't work as I expected, the character has so much speed in him and he flew off the screen.
When I replaced it just like your code "animator.transform.position" patrolling works, but this is not what I want cause he has no rigidbody.
Any help?
thanks bro
What is the best way to combine this with an actual animation controller with normal animations?