A Better Way to Code Your Characters in Unity | Finite State Machine | Tutorial

Ойындар

Show your Support & Get Exclusive Benefits on Patreon (Including Access to this project's Source Files + Code) - / sasquatchbgames
Join our Discord Community! - / discord
In this Unity tutorial, We'll use, from the ground up, the State Machine programming pattern to setup some simple logic for our enemies.
This is a standalone video that walks you through setting up a statemachine for, in our case, enemies. But due to its design it's a perfect setup for characters or NPCs as well, and since the states are self-contained it's very easy to modify.
There will be a Part 2 to this video that expands on the idea by dividing the logic of our states into ScriptableObjects, but this video is meant to act as a standalone, and so if you're interesting in learning how to setup a stateMachine, this is video for you!
Link to Download the FREE 2D Asset Pack seen in this tutorial:
veilofmaia.com/tutorial-asset...
---
In need of some Unity Assets? Using our affiliate link is a great way to support us. It's free, and we get a small cut that helps keep us up and running: assetstore.unity.com?aid=1100lwgBQ
---
Contents of This Video: ------------------------------------------
00:00 - Why Use a StateMachine?
00:47 - What We're Going to Create
01:43 - Setting Up The Base Enemy Script
04:57 - Setting Up The StateMachine Framework
09:22 - Creating the Idle State Logic
10:15 - Creating Some Trigger Checks for State Changes
12:38 - Creating the Chase State Logic
13:19 - Creating the Attack State Logic
Who We Are-------------------------------------
If you're new to our channel, we're Brandon & Nikki from Sasquatch B Studios. We sold our house to start our game studio, and work full time on building our business and making our game, Veil of Maia.
Wishlist our Games:
Wishlist Veil of Maia! - store.steampowered.com/app/19...
Wishlist Samurado!
store.steampowered.com/app/23...
Don't forget to Subscribe for NEW game dev videos every Monday & Thursday!
Follow us on Twitter for regular updates!
/ sasquatchbgames
#unitytutorial #unity2d #unity3d

Пікірлер: 86

  • @masoncrowe
    @masoncrowe Жыл бұрын

    Who else is doing tutorials like this right now?! Killing it man

  • @sasquatchbgames

    @sasquatchbgames

    Жыл бұрын

    holy CRAP!!!! Dude thank you SO much for your support, I don't even know what to say...That's so generous, Nikki and I appreciate it from the bottom of our hearts

  • @chadmoberly7044

    @chadmoberly7044

    Жыл бұрын

    Mason my man... doing lots of good in this world :)

  • @BangBang-zb8sf

    @BangBang-zb8sf

    10 ай бұрын

    Mason is the one who knocks

  • @forbiddenbox

    @forbiddenbox

    10 ай бұрын

    thank you

  • @Dyanosis

    @Dyanosis

    6 ай бұрын

    There are quite a few other Creators/dev doing this right now. Maybe have a look for "state machine tutorial Unity", you'll find at least a dozen.

  • @Steinsdomain
    @SteinsdomainАй бұрын

    I feel like I'll need to watch this like 10 more times before i can even start keeping up xD awesome tutorial though, making it all so clean and look effortless is inspiring

  • @fred1541
    @fred154127 күн бұрын

    As a student , I really learn a lot from your video, which makes my final report excellent in this semester, Thanks~

  • @manningfamilychronicles1601
    @manningfamilychronicles1601 Жыл бұрын

    This is really helpful and well put together. I loved the super quick and casual interface explanation I've been needing to learn that more in depth and that clicked really well how you explained it. Thank you sir.

  • @chadmoberly7044
    @chadmoberly7044 Жыл бұрын

    With the view counts increasing, and the super generous donor under this video, the future looks bright for your channel (AND studio!). Thank you so much for these videos that are honestly worth putting a price tag on. You guys take care!

  • @sasquatchbgames

    @sasquatchbgames

    Жыл бұрын

    Thanks so much! That really means a lot!

  • @shockingchris9809
    @shockingchris98096 ай бұрын

    Just subscribed off this video alone. Some people may hate the amount of scripts here but I love how compartmentalized this is. So easy to follow, even as someone who has yet to implement a state machine yet. Great background story you guys have as well. Hoping the best for you two!

  • @gabrielgauthier5611
    @gabrielgauthier5611Ай бұрын

    I think it's one of the best tutorial I ever encountered, I gained so much just by watching this 16 minutes video. Thank you so much for this !

  • @vbamboo21
    @vbamboo2111 ай бұрын

    This is so nice, informative constructions not only the state machine itself. And the explanation was spot on. Great learning source for newbie like me.

  • @Titrationator
    @Titrationator3 ай бұрын

    A very good tutorial that explains this advanced concept in an easy to digest way. One of the best tutorials for anything I've watched.

  • @Coditionals
    @Coditionals7 ай бұрын

    The worst thing about these videos is they have to be this long and you kept it as short as possible. All of this doesn't favor the youtube algorithm. Really great video! I won't go into tiny details I think that would make it better. Again, thank you so much for this!

  • @AlcadraSoykan
    @AlcadraSoykan11 ай бұрын

    Nevermind, these tutorials are awesome.

  • @khanhhoangquoc1800
    @khanhhoangquoc180010 ай бұрын

    Must be the best state machine i have seen

  • @mehmedcavas3069
    @mehmedcavas3069 Жыл бұрын

    nice. was waiting for that. great jobbb

  • @Jess_stpierre
    @Jess_stpierre Жыл бұрын

    Very informative video! Love your explanations!

  • @psybergames7327
    @psybergames73272 ай бұрын

    Really top tutorial I was always curious of the scriptable object approach although never messed around too much with the idea myself. Although I currently working on a update for a game that already been prototyped and has shown enough interest that taking further. I have changed so much that new Enemy AI was needing done was originally going use a plug in but decided that I would be better to reduce the work load, but after thinking I seen your scriptable object approach. That led me back to previous video. Gave thumbs up and sub well deserved and look foward to the scriptable object use for my game as it will allow to do as you say give the exponential behaviours that will work great for my game as it will have procedural generation aswell so this give real variety abilities. So thank you and big ups for your videos

  • @juanvalderrama644
    @juanvalderrama64410 ай бұрын

    With this you saved my life, thank you very much.

  • @midniteoilsoftware
    @midniteoilsoftware Жыл бұрын

    Oooh, I love the way you showed 3 editor windows simultaneously :)

  • @sasquatchbgames

    @sasquatchbgames

    Жыл бұрын

    Thanks! I would have loved to have synced them up but it would have taken too ong :D

  • @Notreal76
    @Notreal76 Жыл бұрын

    This is a great architecture. Thank you :)

  • @Tayiku
    @Tayiku Жыл бұрын

    Great tutorial, having a big file with 2000 lines is a hell when something goes bad. Would be awesome going a little deeper playing around with the AnimationTriggerEvent method, or using some good practices for where start animations on states, etc.. (I've seen some of your vids, seems you use professional practices, and that is what newbies like me need)

  • @tlotro625
    @tlotro6254 ай бұрын

    Good tutorial. Clean code. Propogates good programming habits. Respects OOP.

  • @mracipayam
    @mracipayam10 ай бұрын

    You deserve much more views!

  • @yungefendi6480
    @yungefendi648010 ай бұрын

    no way there is someone who can follow up on all this shit man

  • @michaelshollaj6428
    @michaelshollaj6428 Жыл бұрын

    very informative tutorial, great job

  • @mohamedmusthafa1057
    @mohamedmusthafa1057 Жыл бұрын

    Wow Very Detailed Explanation ❤

  • @CodeRadGames
    @CodeRadGames Жыл бұрын

    great job as always!

  • @iiropeltonen
    @iiropeltonen Жыл бұрын

    Good stuff. Been thinking about trying statemschines for animals in a game I'm working in.

  • @arc3937
    @arc39377 ай бұрын

    that's really help full, thanks for this tutorial! im trying a multi statemachine for different behavior and that solve the problem for different types of interactions. i was now woundering is the quick override an extension or something, i type all the overrides and im getting crazy now

  • @gbeebe
    @gbeebe Жыл бұрын

    As a professional programmer, who's predecessor's primary thought was "just make it work", that thumbnail hits hard.

  • @sasquatchbgames

    @sasquatchbgames

    Жыл бұрын

    I used to code like that once upon a time. So it hits hard for me too

  • @coemgeincraobhach236
    @coemgeincraobhach2364 ай бұрын

    Unbelievable, thanks!

  • @shubhabrotapal4709
    @shubhabrotapal47096 күн бұрын

    The amount of information is just awesome 🔥, only if u could slow down the pace a little bit it would be easier to watch than pausing everytime , still thanks for the great information.

  • @corvinziegler
    @corvinziegler3 ай бұрын

    Great Video, I ran into a nullpointer exception in fixed update because it was called before the start method and had to get the rb component within awake function of my enemy class

  • @ssbmPi
    @ssbmPi6 ай бұрын

    this video is awesome and contains a bunch of information. you clearly know what you want to get done and seem to implement all of it pretty seamlessly. for me however i am just starting and looking to understand state machines better and this video moves pretty quick and contains a lot of information that im getting lost with, i implemented a state pattern from another creator 'iHeartGameDev' but a few of my more knowledgeable friends said perhaps it was a sub-par example/implementation of a state machine, even though it was functional. do you perhaps have another more 'beginner friendly' youtube video or article that you could recommend to me?

  • @BardockSSJL
    @BardockSSJL8 ай бұрын

    I'm getting a NullReferenceException when I try to call PhysicsUpdate(). But the error goes away if it's called from Update() instead of FixedUpdate(). Any ideas?

  • @BardockSSJL

    @BardockSSJL

    8 ай бұрын

    I just found out Update() is not even being called.

  • @user-dq3jv2xw5v

    @user-dq3jv2xw5v

    8 ай бұрын

    I believe if you left Start and Update methods in Ghost class it somehow overrides Enemy Start and Update with nothing and, therefore, can't find some reference in FixedUpdate.

  • @AndrewBotish

    @AndrewBotish

    Ай бұрын

    Add "StateMachine.Initialize(IdleState);" in the Enemy class Awake function just below the state variables. The state has to be initialized first

  • @dong8912
    @dong891210 ай бұрын

    Would there be any performance implications due to any empty FrameUpdate and PhysicsUpdate calls? I imagine there will be lots of enemies using the Enemy script, some of which will not require FrameUpdate or PhysicsUpdate to be called. Won't this cause some overhead?

  • @kunterkurt9464
    @kunterkurt94644 ай бұрын

    At first, i really appreciate for making such great video. I want to ask about something. I tought, if we use getter and setter structure for both character properties and animation state machine, wouldn't it be more difficult to understand? I'm not expert of this, but maybe we can use switch - case for state machine, and for the character properties (such as durability or move speed) we can use getter and setter form. What are your thoughts on this? Thank you.

  • @blepomorph419
    @blepomorph41917 сағат бұрын

    Noob question and I still get the overall project done but did you install something for Visual Studio to generate those override methods that fast? Mine is configured for Unity but I don't see an option on how to do that. Asking to save a bit of time going forward. And thanks for the straightforward guide.

  • @alxdrksoul
    @alxdrksoul Жыл бұрын

    0:18 //move... LOL!!! thanks for the tutorial, as a beginner this is hard to understand, I might have to watch the video like 10 times before I totally get it, but who said programming is easy xD

  • @TIWNGAF
    @TIWNGAF10 ай бұрын

    When should I use differenct state machines for different systems? I want to handle animation states programmatically in a state machine like this, I also implemented this state machine for my character behaviours. Should I use only one state machine with a variable currentBehaviourState and currentAnimationState or should I split both systems up into 2 different state machines? In my case, the animation states don't correlate always with the behaviour state. How would you guys handle this?

  • @starblinky4091
    @starblinky409111 ай бұрын

    Good tutorial. At 10:15 I thought your enemy was varying his speeds and I was so confused. Trying to find a bug in my code or how yours could be doing that. After inspecting closer it looks like actually you just moved the hero which moved the camera and so it just looked like it was going at a different speed. The background is blank so it was hard to tell. Anyway. I found this pretty useful and will continue along. Thanks for the vid.

  • @JellyMudkip
    @JellyMudkip6 ай бұрын

    Hi! Ive followed the complete tutorial but I cant understand why the movement speed is so slow for me when is chasing the player. Idle speed is the same as the chase one, but chase direction is calculated 10 times small than the other one. Do you know what can it be happening?

  • @Poopymancer
    @Poopymancer6 ай бұрын

    I have an issue with my visual studio that idk if anyone else has/knows how to deal with. I technically can work around it but it is very annoying. In this instance, when you got to the point at 3:19 when you clicked IDamageable to do the quick actions and refractories to put in all that code, my visual studio just doesnt do that. It doesnt recognize thee issue and doesnt know to put that code in to solve the problem. I've had similar issues in the past where it doesnt seem to understand how different scripts connect or something, idk if there's a setting i dont know about that i gotta change or something to make visual studio work better.

  • @piper7521

    @piper7521

    2 ай бұрын

    I have the same issue :\

  • @xRayed85
    @xRayed852 ай бұрын

    Thanks for tutorial, quite informative but I found a problem. I guess you gonna have memory leaks with such cross reference since Enemy knows about State and State about Enemy. Am I right ?

  • @MrBa143
    @MrBa14310 ай бұрын

    Great tutorial! If i use imported animations for my 3D game, i need to use the Events tab in the animation clip, instead of the Events tab in the Animator panel (when creating them IN unity). They are quite different in behaviour. The one for imported animations relies on you providing a function name, and it will then try to find that function and trigger it. Is it possible to incorporate those events into the state machine? Edit: For now i've made a "EnemyAnimationEvents" script that sits on my enemy, which holds functions that the AnimatorController can find for the animation events. These functions will then access the 'Enemy' script and use the respective State instance to call the needed function. So if i have a MeleeAttackEnd event, i will have a EnemyAnimationEvents.MeleeAttackEnd function. This function will call the `_enemy.MeleeAttackState.MeleeAttackEnd` function. I intially wanted to make an empty GO on the Enemy called "AnimationEvents" which would hold seperate scripts with functions. One script per animation, but sadly the AnimatorController cannot search for functions in child objects, it only searches through the scripts on the gameObject in which the AnimatorController resides on.

  • @BMRG14
    @BMRG14 Жыл бұрын

    Great tutorial! But can you please add "FSM" or just "State machine" in the title? (For the future searches)

  • @muajin
    @muajin Жыл бұрын

    Hi. Do you by chance know how to export an android apk from unity? i keep getting some file when i press build and not the apk, also takes pretty long to build. I get a buildmethod error message at the bottom left part of the unity screen.

  • @akashrajak5811
    @akashrajak58112 ай бұрын

    What are less expensive to check distance every frame. Thanks in advance

  • @codenoob223
    @codenoob2234 ай бұрын

    The AnimationTriggerEvent is kinda slow how do i make it fast? I want to change to another animation after the current animation ends but it doesn't, if turn on animation loop time it takes two to three loops to take effect.

  • @MeguhFan
    @MeguhFan Жыл бұрын

    This is really interesting. I'm not sure I've ever seen a enemy/behavior state coding tutorial like this. It's tricky for novices (like me), but I can see how this could save time in the long run making behaviors that can be switched around. Now, random question, I'm starting to interview indie devs on my channel for a series about developers talking about the games they're making, the tools they use, and games that inspired them. Would you be interested in an interview??

  • @midniteoilsoftware

    @midniteoilsoftware

    Жыл бұрын

    I'd be interested in doing an interview.

  • @youtubeofficial2749
    @youtubeofficial27494 ай бұрын

    The AnimationTriggerEvent is kinda slow how do i make it fast? I want to change to another animation after the current animation ends but it doesn't, if turn on animation loop time it takes two to three loops to take effect. How do i fix this?

  • @carlbanfield8906
    @carlbanfield890610 ай бұрын

    one way you could make this video better is to add you using the final product state machine to easily build another enemy using the objects you just created, i know, you'll end up using more prefabs which in essence, are prefabricated lol but it still might help

  • @perssontm1628
    @perssontm16282 ай бұрын

    What I don't understand is, you create the Chase logic in the ChaseState, but what if different Enemies have different chase logic? I guess I don't expect any respond for such old video, but if anyone sees this you are very welcome to explain to me if this is how it's supposed to be used or if it's just an example.

  • @nguyentrandinh8065

    @nguyentrandinh8065

    2 ай бұрын

    I think you just create a new class name like SkeletonChaseState : EnemyState for Skeleton enemy or something else and override update in skeletonchasestate.

  • @perssontm1628

    @perssontm1628

    2 ай бұрын

    @@nguyentrandinh8065 Ah, makes sense I guess

  • @--.--
    @--.--2 ай бұрын

    At this point I realised that my code is sh1t, thanks for showing an example for a better code

  • @brandonmitchell-kiss2533
    @brandonmitchell-kiss25333 ай бұрын

    Shouldn't the reference to player be static, that way you don't need to call it in the constructor and all enemies will share one reference to the player??

  • @Ts1nd
    @Ts1nd Жыл бұрын

    Did you put microphone near keyboard to record the clicks?

  • @sasquatchbgames

    @sasquatchbgames

    Жыл бұрын

    Lol! Yes. I love the clicks

  • 10 ай бұрын

    did not understand shit xD! I will see it again and try to do it

  • @NorinDev
    @NorinDev6 ай бұрын

    why your camera is so close? You spooked me

  • @LmnoSneeze
    @LmnoSneeze7 ай бұрын

    It's always surprising to me that people create scripts in Unity instead of directly in their editor. Creating scripts from your editor means you don't have to clean out the mono behavior bits and allows much higher flexibility.

  • @ekekw930
    @ekekw930 Жыл бұрын

    14:39 why not show us the better way?

  • @cmdrelectrostruck1928

    @cmdrelectrostruck1928

    Жыл бұрын

    I did this for his if else if (!enemy.IsWithinStrikingDistance) { _exitTimer += Time.deltaTime; if(_exitTimer > _timeTillExit) { enemy.StateMachine.ChangeState(enemy.ChaseState); } } else { _exitTimer = 0f; }

  • @patek2385
    @patek23859 күн бұрын

    Why not using Scriptable Objects?

  • @mohokhachai
    @mohokhachai9 ай бұрын

    Decoupling

  • @Arcann_bhp
    @Arcann_bhp9 ай бұрын

    This is so fk complicated my pepega brain is exploding

  • @Coco-gg5vp
    @Coco-gg5vp Жыл бұрын

    First

  • @vertigo2604
    @vertigo260410 ай бұрын

    well, it was interesting, but quite brainbreaking, at least for me

  • @user-ls7oo8mk6k
    @user-ls7oo8mk6k11 ай бұрын

    Плохой пример. Не для игр. Вместо наследования нужно использовать композицию. Создавать врага из разных компонентов, а не создавать один класс Enemy и давать ему интерфейсы

  • @Thefmc2010
    @Thefmc201011 ай бұрын

    nice video, but state machines don't mean better performance, most of the times actually they aren't less performant. state machines generate more garbage and they produce a lot of cache misses. this is not a problem; 99.99% of the time, this will not be impactful for your game. however, 'performance' shouldn't be counted as a state machine's advantage.

  • @danielrodrigorm4173

    @danielrodrigorm4173

    7 ай бұрын

    what do you recomend, i have seen state machine done in the animator with behaviours but i dont know which one is better

  • @IberianInteractive
    @IberianInteractive5 ай бұрын

    you know a lot of programming...but the part where you explain it to people is...horrible.

  • @muajin
    @muajin Жыл бұрын

    Hi. Do you by chance know how to export an android apk from unity? i keep getting some file when i press build and not the apk, also takes pretty long to build. I get a buildmethod error message at the bottom left part of the unity screen.

Келесі