Control Units and Give Orders! (Unity RTS Tutorial)
Вставка
- Опубліковано 20 кві 2020
- ✅ Get the Project files and Utilities at unitycodemonkey.com/video.php...
Let's make a Simple RTS Control System to Select our Units and Give Orders.
This is a great base for you to expand upon, add more actions, different types of units, etc.
Stay tuned for an upcoming video covering how to make Custom Animated Cursors so we can make the game look better and give the player more context.
Control Units and Give Orders in Unity ECS!
• Control Units and Give...
Modular Character System in Unity
• Modular Character Syst...
Patreon Sponsor: www.badadventurer.com/
We're going to start off with a basic Unit standing Idle.
First we capture the Mouse Down and Mouse Up events and store the Mouse World Position, using that we can then use Physics2D.OverlapAreaAll which returns all the Colliders within two points
Then we create a script to identify our Units and ignore objects like Rocks. We add a Visual for the Unit Selection and the Selection Area.
After that we add the ability to give our Unit a simple Move Order. The Unit is handled by the Modular Character System created in a previous video so we can easily add some move behaviour.
With the Units receiving orders then we dynamically generate some positions around the Target Move Position and send each unit to a different position in order to prevent overlapping.
And with that the RTS Control System is done!
You can use this as a base for your RTS Games and Expand upon it by adding more actions and behaviours like Attacking Enemies, Constructing Buildings, Gathering Resources and so on!
If you have any questions post them in the comments and I'll do my best to answer them.
🔔 Subscribe for more Unity Tutorials / @codemonkeyunity
See you next time!
📍 Support on Patreon / unitycodemonkey
🤖 Join the Community Discord / discord
📦 Grab the Game Bundle at unitycodemonkey.com/gameBundl...
📝 Get the Code Monkey Utilities at unitycodemonkey.com/utils.php
#unitytutorial #unity3d #unity2d
--------------------------------------------------------------------
Hello and welcome, I am your Code Monkey and here you will learn everything about Game Development in Unity 2D using C#.
I've been developing games for several years with 7 published games on Steam and now I'm sharing my knowledge to help you on your own game development journey.
You can see my games at www.endlessloopstudios.com
--------------------------------------------------------------------
- Website: unitycodemonkey.com/
- Twitter: / unitycodemonkey
- Facebook: / unitycodemonkey
Here's an RTS Tutorial! Would you like to see more? I've always wanted to make a mini-AoE!
🌐 Have you found the videos Helpful and Valuable?
❤️ Support on Patreon www.patreon.com/unitycodemonkey or get the Game Bundle unitycodemonkey.com/gamebundle.php
Great vid. I'd like to see more rts stuff.
More rts videos would be really appreciated! :)
Please continue great monkey coder😍
Yeah, I am planning on leveraging this into a formation system... out of curiosity, i grabbed the files for your "player movement" tutorial but it was lacking the sprites/textures... is that intentional or am i missing something?
A mini-AoE from scratch would be awesome
Wow RTS tutorial.. we definitely need more of these from you!
This video is a priceless gem! It's hard to find good RTS unity tutorials out there. I was doing it on my own, it kinda worked, but then I stumbled upon your video, which was doing the same but insanely simpler! LOL
Who else love to see more RTS Tutorials? Count me in 😍
This is one of my favorite genres, today I have met your channel (subscribed), wow you have surprised me, I have always had a motivation to create a video game focused on this genre, it would be very amazing if you could do more tutorials focused on this genre, which is very difficult find on youtube. You are an excellent instructor, I appreciate people like you who share their experience, thanks
Yes please, an RTS series would be great! Thanks for your videos!
Man I am crying saying I LOVE YOU
.....MAN HOW GREAT YOU ARE HOW MAGNIFICENT YOU ARE....WOW THUNKS A LOTTTT....LOVE YOU PREACHING YOUR WORK A LOT
I was searching how to make a game similar to AoE (maybe not as complicated) and I found this incredible channel. Please post more like this! :D
i have always wanted to learn to make a rts similar to mowas2 and Company of heroes so I am very happy for this tutorial
Stronghold Crusader Style Units Selection. I really liked this tutorial.
Would love to see some more RTS tutorials
This is incredibly useful! My friend and I are currently making a sort of RTS tower defense game, where you can order troops around in the style of Company of Heroes and build fortifications. I am currently working on the scripts for troop movement and needed an idea for how to move multiple troops in a fixed squad, without them running into each other.
However I want to use a grid system to place the troops and buildings on the map and to keep the troops from running to the same position.
Honestly, your tutorials not only help for special use cases, but also show programming techniques that can be used for other stuff. FAR more helpful than most stuff I have found, especially due to the explanations.
I'm glad you found the videos helpful!
If you're looking for a Grid System I covered something like that here unitycodemonkey.com/video.php?v=dulosHPl82A
Instead of buildings you could place down Units, so it would be kind of like Civilization
Then maybe use the code from this video to dynamically calculation the base unit positions and make them go back to those positions after they attack something
thank you! best tuts on the topics which are nowhere else to be found! :D
Hey man, I just wanted to tell you I am a Dev (web) and I worked as an artist in games for a while. i stumbled across your channel while i was looking to get back into writing some code for a couple of simple games for me and some friends to play for a laugh.
This channel is amazing and you do a fantastic job, once i had watched a little of it i went directly to steam to get battle royale tycoon (which looks great btw) and picked up your bundle on your link, even if i never played the games i wanted to give you a little thank you for all of your hard work!
Thanks! I'm glad you found the videos helpful!
Please more rts tutorials so that i can make my own C&C game or RA2 or AOE :D
And KKnD
@@user-bl2wi6cn1k Yes :D
yes! i so want to make an Empire At War knock off
@@fingerflowerstudios yes thats a great game too :)
Generals
Great video! I would be really happy about a rts series! :)
YEEEEEEEESSSSS finally!!! some RTS series from one (if not THE) best channels for Unity on UA-cam! 😎♥️🥰👍👍👍 do not stop the series please this time! Game development is the hardest form of software development..and RTS the hardest form of game development...so few and rare complete RTS easy and good tutorials out there! there is a huge gap in today's version of Unity on this topic! be the protagonist the opportunity for countless vies is there! 🥰
next videos should include base building...and gathering 1 resource. and i am going to become a Patreon now how did i skip that? 🙄 RTS ♥️4ever
This isn't just useful for RTS and that's what I love about your videos. I'm currently learning bits and pieces for my action RPG. Keep up the great work!
Thanks! I'm glad the video helped you!
come back to this series please. everyone is asking for this!
great tutorial. has a lot of good info on how to make an rts. i learned a lot
Awesome! Good job and thank you.
Great tutorial! 👍🎓 Looooove real-time strategy games! ❤️🤓
I used to play Red Alert all day long!!! 😝🤪
Great Courses! Yup there you go!
exactly what i need!! i love you so much...(bear hug)
Thanks, this video helped me a lot
Great example thanks!
Definitely one of the topmost channels for Unity tutorials, maybe the best even.
I'm glad you like the videos! Thanks!
@@CodeMonkeyUnity You are very welcome. And thank you very much for the reply.
Like first, then watch hehe
Hello! I would like to set the tiles in which the units stands as not walkable, so they cannot stay in the same one thus avoiding overlapping. I've thought about adding a collider to each tile to detect when it is occupied but I imagine it would be very expensive, and I have also seen the RaycastWalkable function but would not want to call it constantly as it must also be expensive. could you give me any hints on how to do it?
Thank you man, you've gained a new Patreon Subscriber.
Awesome! Thanks for your support!
Great tutorial thanks a lot
again a great video
Amazing tutorial
that's what i want! thanks!!
This is excellent work.
It would be great if you could link the actions in the next video to the Stats system you introduced in the Stats Radar Chart video.
Will there be group selection, obstacle pathfinding and enemy combat tutorial using this rts system?
Love u some much, thx for the video :)
Thank you man at the future I just want to be a rts game maker but first i started at 2D game
This is very useful
Nice video good job 🖒👌
Great video as always - please show how to select all of the same type of units on key down + mouse down.
hello you can edit the formations of the soldiers for example 5 x 6 or 7 x 8 or you would have to do it selecting one at a time
Any advice for adapting the unit grouping in `GetPositionListAround` for a 3d game where the units are along X and Z? I've been tweaking and they just keep standing in a straight line.
Figured it out if anyone else is stumped here: in the `ApplyRotationToVector` method move the `angle` variable to the y position. this creates a circle around the y axis which is what you'd want for a 3d game whereas the `angle` being in the x position like in the tutorial is what you'd want for 2d.
Hey Code Monkey, will this tutorial go together with the Builder Defender course you made? I am currently working through that course and want to make an RTS.
Well done :-)
I can't get a confirmation email to be able to download the Utils. Is there no way to get around that and have a completely from-scratch project?
a method for getting the mouse position:
private Vector3 GetMouseWorldPosition()
{
Vector3 mousePosition = Input.mousePosition;
mousePosition.z = -Camera.main.transform.position.z;
Vector3 worldPosition = Camera.main.ScreenToWorldPoint(mousePosition);
return worldPosition;
}
awesome! im gonna make a starcraft in unity now. (says a guy who just started learning unity)
Go for it! Start small and do one tiny thing at a time!
This video is very helpful, thank you Code Monkey.
Still waiting a complete RTS series :(
Just wanted to say your stuff is really good. Honestly it's better than Brackey's stuff.
Thanks! I'm glad you like the videos!
Question:What task manager should I use for my game?
Please please make more RTS tutorials!
Could you do a video on local avoidance, please?
Awesome video brother!!
Do you share the sprites in the downloadble files as well?
Great video. I've played your top down shooter and I'd be cool if you do a video about how the turret works. Specially how to do the red lines closing and then shooting when closed.
I covered the boss fight in detail here ua-cam.com/video/qZC1VYWnHZ8/v-deo.html
The lines are just visual, there's a simple float storing an angle and its counting down, when its small it enters the shooting state
@@CodeMonkeyUnity Thanks!
Nice video. It is quite enjoyable to see the units move in 2D.
However, I have a problem with moving to 3D. In your utilities, does the GetWorldMousePosition function work in 3D? Because I only get the coordinates of the camera, wherever I click.
I'm having the same problem. I just switched my camera from Perspective to Orthographic, and use either WithZ, or change the 0'd .z to .y, hopefully this works, at least my coords now change between click and release.
Edit: My results were off a bit, so now I'm just just doing a raycast, ScreenPointToRay(mousePos), and using hit.point. Seems more accurate when I get to selecting colliders, and also works fine in Perspective.
Thank you. I found a RTS tutorial in 3D: ua-cam.com/play/PLm1w78-UUlMJ-S8Apf96YzzAaa2yfZzAx.html
It's interesting, because the way of doing things is quite different, which allows you to learn something else.
Yeah that function is made for 2D, in 3D you need to do a Raycast.
You can download the project files for the Wash Your Hands game where I did make mouse interaction in a 3D world.
ua-cam.com/video/q9pe-wH7eZ8/v-deo.html
@@CodeMonkeyUnity thanks !
I made a function GetWorldMousePosition3D which works, and which I already use to instantiate trees where I want during the game, but I came up against a problem with the selection area: changing the scale also modified startPosition.
It was just a pivot problem to put on the bottom left, but what I did not know is that you must not only apply the changes to the texture, but also reload the sprite with the updated texture. So much time lost for a texture of 1 on 1 ^^.
Great 2D tutorial, it works perfectly. Thank you !
Awesome video as usual. But why are you not using a layer mask to check for collision instead of using GetComponent? I understand getting component is usually more expensive
Layers are used for tons of things like Rendering, Physics, so I don't like to use them to simply identify a type.
But yes if you happen to have extreme performance issues in that one line then querying for the layer would be faster.
very good tutorial! just one doubt ! IMovePosition and IMoveVelocity where do they come from or which video to have it as a reference? From already thank you very much !
I covered interfaces here ua-cam.com/video/MZOrGXk4XFI/v-deo.html
And I used them pretty extensive in the Modular Character Controller ua-cam.com/video/mJRc9kLxFSk/v-deo.html
With regards to this system it doesn't matter how they are implemented, as long as they do what they're supposed to do
Great video, but wouldn't it be better to make the numbers of units and the distances dynamic and not hardcoded? What if I want to select 50 units?
Hi Code Monkey.
At 08:55, after I input the offset to the sprite, when I select the SelectionAre, the transform position arrows didn't snap to the lower left corner as In this example. Mine stayed in the middle.
Do you have an idea as of why this may be happening?
Nevermind! I noticed the selection box was being drawn correctly BUT behind the terrain sprite.
Fixing it now!
Loving the RTS tuts!
Hey my selection area moves slightly towards my mouse when I drag it in any direction. I didn't change anything in the code
Hi, I am planning on making an RTS game solo, and was wandering if your Utils package is ok with being used commerically? Thanks.
Yup feel free to use it in your projects, free or commercial. Best of luck with your game!
It a good tutorial. At 15:47 to 15:52, the group is not moving at the most efficient route. For exemple, I notice some unit are taking long route to get to their destination. Like the unit from the far right ended up at the left side of the circle. Is there a way to decide their destination so that the group would reach to their destination faster rather than each unit take the shortest route to the destination?
Sure just add some more logic to choose which unit goes to which position instead of just based on index
I try to build a mix of rts + horror, you have any suggestions for this mix?
I love your videos. Im making a mini RTS for a school final project and im trying to figure out how to do it where you see the UI multiselection ( like in StarCraft ) but I can only get 1 UI button to spawn or it keeps spawning indefinitely .
do you have a tutorial on this or soon?
You need to cycle through all the selected units and spawn a UI element for each of them.
I very much want to continue doing more RTS videos so more coming soon!
@@CodeMonkeyUnity i was doing that. My problem seems to have been that i was checking every frame instead of checking and populating after a selection
Yep there we go
I'd love to see more RTS tutorials, but why aren't you using a navmesh?
Suggestion: you should make a video doing all the HUD logic of AOE and Warcraft 3. How to click in a unit and turn on some icons in the UI. In case of buildings, icons that spawn units when pressed and in case of units icons that uses skills or something else. All these functions applied to single unit and to multiple units if they're selected. And some icons that represents the selected units (like in Warcraft 3).
Thanks! Hope you will upload some tut abour UI in near furture.
Hey Codemonkey, i'm having trouble with creating enemy ai, i made Field of view which checks distande, angle and shoots ray in order to detect play (and sets visible = true), but is there any way something like OnRaycastExit? my ai behaviour is too simple patrol(if unvisible) - shoot (if visible). I want to add Searching state when player exits FOV.
There's nothing built-in but sure that's easy to do, you store a boolean like isPlayerInFov, then you check the angle to the player, when it leaves you set the bool to false and fire off an event.
@@CodeMonkeyUnity then enemy's initial state will be searching (since IsInFov = false), i want them to patrol and go to searching state for only 10 seconds only when player enters the Fov and Exits it
Is there any way to add on a way for RTS units to attack a target (E.G Right clicking once selected on an enemy?) I've been trying to search through your videos but i can't seem to figure out a way to do this ^^; Great video though!!
You just need to capture clicks on top of an enemy, add a Collider and do a Raycast
I made some videos a long time ago that did that
ua-cam.com/video/cxSkhlWAaqI/v-deo.html
ua-cam.com/video/sb9jnpN9Chc/v-deo.html
Hey, I'm making an RTS and there's a lot of architecture problems that I can't confidently understand. First of all, your UnitRTS class has a method for sprite activation, which I don't think makes sense considering the class should apply to enemy units which may not be selectable. Would it make sense for player and non-player units to have different prefabs with the UnitRTS component and a separate component for handling sprites and stuff for that prefab?
Additionally, if you remove the Awake method from the unit class and give it a transform reference, you could change the code so that it doesn't have to inherit MonoBehaviour, which could allow the unit to move in the background when the GameObject is disabled. Is this a dumb idea?
The goal in the video was Unit control so it wasn't meant for also controlling enemies, for enemies you probably don't want direct control so you could either have a generic script applied to both types or one script for each, depends on how many abilities are common to your friendlies/enemies.
Sure you could make your whole game non-monobehaviour so the logic would not depend on any game object. That's exactly what I did in my Battle Royale Tycoon game. The game objects are only used for visual, all the logic is handled in regular C# classes.
Hey, love your channel been watching a lot recently. I have a question- do you think this type of movement would work in a mobile game well? If not any recremendations?
I havent played any mobile RTS so not sure what are the best practices but sure this could work
Just wondering, would it not be quicker to use layers to check if a unit is selectable, rather than checking for a script?
Sure that's another valid approach, the performance wouldn't be an issue since it happens so rarely. If all of your Units are already set in their own layer that would work but in order to give them orders you need to get the component.
Hey Code Monkey, I understand this tutorial but am getting an error for "IMovePosition" everything else in my scripts works fine but im stuck here. Any help would be greatly appreciated.
What error? I covered interfaces in detail here ua-cam.com/video/MZOrGXk4XFI/v-deo.html
Is there a video explaining how path finding was implemented ? I watched the A* one and it doesn't seem to work with multiple units correctly. You also mentioned flow field which I couldn't really make it work in my case where I want to store one unit in each cell of the grid
I didn't implement pathfinding in this demo, it's really just dumb straight movement.
Flow field is indeed the main option for RTS games with lots of units. You can still keep one unit in each grid position, you can check the next grid position for each unit based on the vector, and check if that one is empty or not.
Or only check at the destination, when getting that point look for the closest empty grid position.
@@CodeMonkeyUnitythe problem is most of the tutorials I came across seem to use physics raycast to handle units movement
I tried to combine the grid system with the physics logic but it gives weird results.
I'll give it another shot tho,
Thank you so much!
@Code Monkey I am getting this error when running the pathfinding script
NullReferenceException: Object reference not set to an instance of an object
MovePositionPathfinding.SetMovePosition (UnityEngine.Vector3 movePosition)
(at Assets/_/Stuff/Videos/ModularCharacter/Scripts/MovePositionPathfinding.cs:24)
UnitRTS.MoveTo (UnityEngine.Vector3 targetPosition) (at Assets/RTSControls/Scripts/UnitRTS.cs:21)
GameRTSController.Update () (at Assets/RTSControls/Scripts/GameRTSController.cs:73)
I cannot figure out this error. I have not made any changes to your code. Can you please help me? Thanks..
Hi ! Very useful video. Tell me if there is anything in your videos about changing weapons in your hand, such as changing a sword, axe, or spear... (I want to understand how to better implement weapon changes in skeletal animation)???
Yeah that's going to be very dependent on what animation system you're using, I haven't covered the standard unity animator yet.
I made the Ability Bar but its using my custom animation system ua-cam.com/video/obvUYZK-kGE/v-deo.html
@@CodeMonkeyUnity Thank you very much for your responsiveness !
Thank you so much
But you used overlabareall in physics2d
What can I use instead of this in 3d?
Probably OverlapBox
Thank you so much i did it
Can you make terraria like project? I create game like that but I can't make random generator and mining-building system
Hey there! I'm using Visual Studio and Unity 2020.1 and when I type Vector3 all it gives me is "Vector32" in the selection box. All vector code is missing... is there something I've messed up? I didn't remove anything from the original startup either. All collections are being called, as normal.
Vector3 is one of the base Unity structs so it seems like your Visual Studio isn't recognizing the UnityEngine namespace. Try manually installing Unity Tools for Visual Studio
@@CodeMonkeyUnity I found it! Visual Studio wasn't selected for Unity's third party coding platform on my project. Once I went in and changed that, it started recognizing Unity's "using" platforms
I want to ask you, is there a video that explains how the player jumps in (3D) a third-person shooter I need for my game, it's been two days, I'm looking for a jump that fits my game, but there are mistakes that happen to me, and your explanation is perfect and understandable, so I need your help, big brother
I made a Jump here ua-cam.com/video/DEGEEZmfTT0/v-deo.html
It's in 2D but the logic is the same in 3D, just need to use 3D components instead.
So do a Physics.Raycast instead of Physics2D.Raycast
After adding the utils package I get an error but no idea where it's coming from. Any tutorial on how to use the utils package?
What error? Each function/class in the utilities solves a specific problem so you just use what you need
When I begin my game with two instances of the player prefab, for some reason the second one immediately begins to move towards the first. Anyone else run into this issue, or have some idea?
edit: turns out they're actually getting sucked to the grid origin. I guess it must be the velocity, I usually just do raw input... who knows lol.
I tried using your code for the different positions that the units go to so they don't overlap but i get the unity error ' the name 'positionList' does not exist in the current context' (for your line 90 as of 14:22 in the video), I am puzzled as to why this is happening, can you please help?
It means you don't have any variable named "positionList"
@@CodeMonkeyUnity Oh yeah, i just missed a line of code. Thanks!
Does anyone know how to make it so that my troops don't go to a position in the formation that overlaps with other troops in the selection? Mine are in the shape of a pill/capsule right now, so they tend to overlap each other a lot, even if the distance is increased
nice
so does that mean only 30 units can be controller at one time with this script? since, at least from the codes, rather than dynamically, calculate what to place within the space, it's calculating position-based on area set beforehand. Unless I missed out something..
You can generate as many positions as you want to control an any number of units.
I only generated as many as I needed but if you need more just calculate more
@@CodeMonkeyUnity Ah Thanks. Just wanted to make sure I understand the code right.
Hello , is there a way to easely get the mouse position for "currentMousePosition" rather than using a utils , i prefer not using them , thanks in advance
The function just does mainCamera.ScreenToWorldPoint(Input.mousePosition);
question: why you don't initiate the lists for example in your code the moment in the same line you are declaring them? why go through the hassle to remember to do that in another state? 🙄
Just because I don't like that pattern, I like to separate declaration and initialization.
Works the same though so if you prefer that pattern then by all means use it.
So the target positions wouldn't take into account any blocked areas right?
Correct, you would need to add that feature if you needed it. The implementation depends on how you are defining blocked areas.
Should I test this out with 19.3.11f11 + Universal Render Pipeline or 2D ?
This was made with URP 2D yes
where do we get the assets or tutorial on how to get to where this video started?
Each tutorial is on a specific topic. For example this one is on handling RTS controls but you can combine that with any number of visuals. The control system and the visuals are separate.
The specific visuals that I'm using here is a custom animation system based on dynamically modifying meshes unitycodemonkey.com/video.php?v=11c9rWRotJ8
Then the mouse works differently in 2D or 3D unitycodemonkey.com/video.php?v=0jTPKz3ga4w
unitycodemonkey.com/video.php?v=3zxTigjJr24
im having some problems, it says "error CS0103:the name 'utilsclass' dose not exist in the current context" how to fix?
The name is UtilsClass and not utilsclass. Also those are my own utilities, not something built into Unity so they need to be in your project in order to use them
Hey i have a question.
How do you make the map or ground pls help me thank you
Its just a simple texture drawn in Photoshop
grab a "seamless texture terrain" from google search and save as a PNG. then in unity assets - import new assets. change to texture type sprite type in inspector, mesh type full rect then drag it into the scene, on the instance that was created set draw mode to tiled and width and height to say 20 and 14 (that worked for the turbosquid texture I used)
When move the unit with the right mouse button, I want to make a script to stop move when it hit the wall, so I see the 'Modular Character System in Unity' video, and I add the script 'PlayerMovementMouse '.
but it did not work and go through the wall.
You need to incorporate some kind of pathfinding system if you want it to avoid walls unitycodemonkey.com/video.php?v=alU04hvz6L4
unitycodemonkey.com/video.php?v=46qZgd-T-hk
@@CodeMonkeyUnity Thank you for reply
it is posible to implement this with some kind of path finding and obstacle avoidance??
oh srry i got it, with the modular system there is a path find didnt?
Yes, if you're using a modular character controller then it would be as simple as adding that module.
If not then you just need to implement a call to your pathfinding system when you tell the unit to move and maybe also use pathfinding to validate unit positions
2:32 I try to move the script and it says to me: "the script don't inherit a native class that can manage a script"
If anyone's opening this up after some ECS updates and getting errors, here's some fixes:
Time.deltaTime is now Time.DeltaTime
World.Active.EntityManager is now World.DefaultGameObjectInjectionWorld.EntityManager
This fixes the compile errors, now to figure out how to get the rest of it running
When I play the scene, my units will automatically move to the center for no apparent reason, then after that, they work fine. How do I make it so that they stay where they are when I play the scene?
On Start() set their target position to their current transform.position