20 Advanced Coding Tips For Big Unity Projects

preview_player
Показать описание
End spaghetti code! Learn the tools you need to write scalable, well-structured, clean code. So many game developers are forced to scrap their ambitious Unity games because they don't know these tips. As a young, self taught game developer, I didn’t discover these tools and techniques for years. Hopefully this video will help you to skip the learning curve and expose you to some of the more advanced programming devices that don’t get enough attention from the plethora of beginner Unity tutorials.

//chapters
00:00 - Intro
01:12 - Variable Names
02:11 - Comments
02:58 - Encapsulate in Functions
03:36 - Plan Your Code
03:57 - C# Properties
04:38 - Serialize Field
05:02 - Component Architecture
06:00 - Enums
06:25 - Coroutines
07:32 - Invoke/Invoke Repeating
08:03 - Structs
08:50 - Singletons
10:38 - C# Events
12:34 - Unity Events
12:56 - Interfaces
14:34 - Inheritance
17:50 - Scriptable Objects
19:15 - Custom Editor Tools
20:25 - Use Version Control
21:00 - Refactor Often
21:38 - Outro

//socials
TikTok: tesseractyt

//long description
So you finally decided to begin work on your “dream game”, a fantasy MMO RPG sandbox battle royale powered by a blockchain economy. What could possibly go wrong? Then, two months later, progress comes to a grinding halt. You have scripts that are a thousand lines long, you’ve forgotten what your old code does, adding new features means you have to rewrite three old ones, every script relies on every other one, and overall, your project becomes an unorganized, unmanageable, confusing, dumpster fire of spaghetti code. Tragically, you are forced to scrap the project and give up on your game dev dreams. Sound familiar?

There are hundreds of hours of Unity tutorials online, but very few are geared towards more advanced developers aiming to create large scale commercial games. That’s why I’ve compiled a list of some of the most valuable unity coding tips that I’ve learned over the years, along with examples of how I’ve actually used these techniques in my own game. Hopefully, by the end of the video, you’ll have the tools you need to write scalable, well structured, clean code that won’t come back to bite you down the road.

//music
Evan King - Nightmares and Violent Shapes
Internet Historian: Sthlm Sunset - Ehrling, A.X - Ehrling, Night Out - LiQWYD
Music from Uppbeat (free for Creators!):
License code: VVIYH4NIZH0ARSHF
License code: AMYFJECHAZAJGCMI
License code: Z6V3SJ5TMSRFUKKU
License code: F9CFDRM8JFBQIVOD

//hashtags
#unity #unity3d #unitytutorial #gamedevelopment #coding #programming #indiegame #cleancode #codingtips
Рекомендации по теме
Комментарии
Автор

Here's a couple of notes/corrections that people have pointed out in the comments:
🔵 The tip I called "getters and setters" should've been referred to as C# properties
🔵 Use Invoke(nameof(yourFunction)) instead of using a string parameter. Also coroutines are normally the better option because they don't use reflection.
🔵 Call a coroutine with StartCoroutine(myFunction()) instead of using a string. Also look into async methods as an alternative.
🔵 Use the event keyword when you declare an action variable
🔵 Singletons are a contentious topic and are probably better suited for small to medium size games. Use them carefully or look into dependency injection as an alternative.
🔵 I made a mistake in the code for implementing a singleton. Don't destroy the original instance, destroy the new class. It should be
if (Instance != null && Instance != this) {
Destroy(this);
return;
}
Instance = this;

🔵 Scriptable objects are not recently released… oops

TesseractDev
Автор

Great video! It's awesome to see someone so young already so focused with writing good clean code!

CodeMonkeyUnity
Автор

8:00
for Invoking a method, it's better to use nameof(MethodName) instead of literal string so the name will be updated when you change the method name, as well as being able to view it with the method references, and the best of all, auto completion

playuno
Автор

this is "stuff i heard about but didnt quite understand fully and i havent looked it up yet" THE VIDEO at least for me it is. i will probably come back to this a dozen of times. great work!

AcIdBARRY
Автор

Me: Moves hand for a sec
Unity: *Reloading Domain*

agbdev
Автор

Something slightly more advanced, but that will help immensely once you get into the habit is unit testing.
This is probably easiest to do through the Unity Test Framework, this allows you to write code that tests a single function, and by keeping it around you'll be sure the feature isn't broken in a future update.

Say for instance you want to add recoil to your weapons, pushing the player back a bit whenever they fire. By writing a unit test you can ensure that the push is always opposite the direction fired. That way if you later add a weapon that fires in random directions you might discover that the random vector added to the aiming direction didn't get transferred to the recoil.

It's not just useful for catching errors in the future, but it also helps you write good code. If you want to test something but it's hard to do then it's often a sign that you did something wrong in the first place. For instance, let's say you can't test the cover mechanic because it requires the map to be loaded, and the timer to be running, and the network code to be loaded. That means your cover mechanic is dependent on all those other systems and is simply doing too much.

One nice way to ensure you test your code is to write the test first, so instead of adding the recoil to all the weapons *first* you add the test to make sure the recoil is pushing the character back first. Then you run your tests, this will give you a red flag for this feature. Then you add the feature and test again, now you get a green flag. Then finally you clean up by refactoring things before moving on.

In short: red-green-refactor.

The benefit of this is that you are sure you wrote your test properly. If for instance you check for the recoil that you don't have in the game yet, and the test says it's working then you know you have a bug in your test code. Same with running the test after adding the feature, now you're sure it can tell that the feature *is* working properly. That way you can be sure the test will alert you in the future if a bug creeps in.

It's a part of agile programming, if you want to look it up for more details. By using that I could handle a 300k+ lines of code project just fine on my own. Before adding unit tests there was always the concern that I forgot some edge case or broke existing functionality, and it was simply too much to manually test.

Finally, singletons can be hard to unit test, but you can make them work by adding extra code for swapping out the instance with a test one. Usually by changing it from a specific class to an interface instead. Then you can replace the singleton with a test version that just says okay to things you're not interested in testing at the moment. At that point it might be easier to simply give the class the interface implementation directly through a property, which is basically what "inversion of control" is about. Having external code provide the dependency your code requires instead of having it get the dependency itself.

Sylfa
Автор

As a developer with 5+ years of experiece who recently started to learn Unity and C# I would like to state that this is the best, most informative and well structured "tips" video I have ever seen. Great job!

copypaster
Автор

You should use the C# "event" keyword in order to protect the event's delegate (Action) from being invoked from outside the class in which it is declared. Without the "event" keyword, you risk the event being triggered at the wrong time.

GamesEngineer
Автор

Really wish a video like this was around back when I started Unity development six years ago, these really are some of the top priorties that new beginners should learn. Great video!

explosiveeggshells
Автор

Your video made me realize, that I am no longer a beginner. I understood all your tips and will be using them asap. Thank you so much for this video,

MosolaStudios
Автор

I have been working in Unity for many many years now, and these are some perfect examples of paradigms and patterns that I have learned over time after coding myself into a corner. One of the better unity tip or even coding tip video I have seen in a long time. I'm gonna save a link to this video in the root of my unity project as I develop so I can watch it from time to time as a reminder to not write silly code anymore. Great work, keep it up! =)

simonandersson
Автор

Events and interface makes the code modular and decoupled alot that once you start using it, u will appreciate it alot

Rahulsingh-theraha
Автор

I'm not actively using Unity at the moment, but a lot of these are solid pieces of advice for programming in general.

TheJaguar
Автор

ENUMS and Serialization:
Be very careful when adding new enum values/options to an existing enum definition if you have already started using it in your project and you have that enum serialized anywhere (scene or prefab). Unity serializes enums as numbers by default, starting at 0, if you add a new option to the enum make sure that you at it at the END of the definition list because otherwise you may be 'redefining' what already serialized enum data will be deserialized back to.

Sindrijo
Автор

i really like this vid, he really helped me get into the mindset of developing a big project and even made it seem a little less daunting by splitting things up and haveing your code correlate with itself, thanks

IsKid-tbwq
Автор

Most importantly: LINK THINGS UP IN CODE!
I think this is an often-overlooked issue with projects that become bigger. The Unity UI is great for novices and small projects, but in the end you want a debuggable and searchable dependency overview.
The ironic thing is that it’s not a full item on your list, but a side comment about your preference.

Anyway: some more tips:
- return an IEnumerable on the public get of a list or array, so callers can’t change it that easily (except for casting and other reflection utils)
- end multi-line enums and list initializers with a comma, so it’s easy to add, delete or reorder the items.
- coroutines run on the component so make sure to not disable it. Better yet, have a “coroutine” instance that you can address at any point.
- use the nameof(Function) variation of Invoke to get compile-time checks on your function name.
- scripts should destroy themselves, not the other Instance (whoops)
- don’t go overboard with inheritance and interfaces when s nice _type enum and case statement will do. This will often create less messy code, especially when they do similar things with different values (easier to compare the implementation differences at first glance)
- if you have lists of content (levels, weapons, avatars, spells) consider going for a data-driven method and loading stuff like textures and scriptable objects through addressables and a parameterized path. Instead of hard-linking it in Unity UI. Your loading time will thank you as well.

lucbloom
Автор

You came out of nowhere and your channel blew up! Glad I ran across this gem. Great work on this. I've learn alot in the pass 22 minutes.

SkaiCloud
Автор

This video made me feel so much better about the things I have been confused about at school, thank you so much for putting this together.

danibettlemuse.
Автор

I have to admit, that when I saw 22 minutes long video, I thought this is us yet another artificially stretched video about Unity basics... and it frankly is, to some extend. You managed to cover the basics but I'm such pace, that I had to pause it several times and in the end I wished this would be bit longer. To cover these basics, you would otherwise spent hours of searching for other fragmented pieces of such important basics.
This is very well done my friend... Keep up!

MartinHolan
Автор

This is the video that i longed to have for years. I only tangentially got into programming and only ever learned what was needed to get the job done. This video made so many of the concepts that i kinda knew about but never fully grasped, trivially easy to understand. Stellar work on this video and many many thanks <3 !

DonC