Why you should NOT make everything PUBLIC!

Поделиться
HTML-код
  • Опубликовано: 1 авг 2021
  • 🌍 FREE C# Beginner Complete Course! • Learn C# Beginner FREE...
    🔴 Watch my Complete FREE Game Dev Course! 🌍 • Learn Unity Beginner/I...
    🌍 HumbleBundle MEGAPACK cmonkey.co/humblebundle
    ✅ Unity Summer Sale (ends soon) assetstore.unity.com/?aid=110...
    🌍 Get my Complete Courses! ✅ unitycodemonkey.com/courses
    👍 Learn to make awesome games step-by-step from start to finish.
    🎮 Get my Steam Games unitycodemonkey.com/gamebundle
    💬 As you're starting out you might learn to set things as public in order to expose them in the Editor.
    In this video I tell you why you should NOT do that!
    The reason is to write good clean code that minimizes code complexity. The less accessible your variables are the better.
    If you have an error with a variable that is set to public, you don't know where the error comes from, it might be in that class or any other class in your entire code base since every class can modify that field.
    However when you set it to private you make sure that any issues that occur have to be happening from within that class, that really helps on keeping a smaller mental model of what your code is doing.
    And if you want to expose a variable in the editor, simply use the attribute [SerializeField]
    That way you keep your code nice and clean but still keep it editable in the Editor.
    🌍 Get my Complete Courses! ✅ unitycodemonkey.com/courses
    👍 Learn to make awesome games step-by-step from start to finish.
    🌍 Get Code Monkey on Steam!
    👍 Interactive Tutorials, Complete Games and More!
    ✅ store.steampowered.com/app/12...
    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
    🎮 Grab the Game Bundle at unitycodemonkey.com/gameBundl...
    📝 Get the Code Monkey Utilities at unitycodemonkey.com/utils.php
    #csharp #unity #programming #unitytutorial #gamedev
    --------------------------------------------------------------------
    Hello and Welcome!
    I'm your Code Monkey and here you will learn everything about Game Development in Unity using C#.
    I've been developing games for several years with 8 published games on Steam and now I'm sharing my knowledge to help you on your own game development journey.
    I do Unity Tutorials on just about every topic, Unity Tutorials for Beginners and Unity Tutorials for Advanced users.
    You can see my games at www.endlessloopstudios.com
    --------------------------------------------------------------------
    - Other great Unity channels:
    Unity - / unity3d
    Brackeys - / brackeys
    Dani - / @danidev
    Jabrils - / @jabrils
    BlackthornProd - / @blackthornprod
    Sykoo - / sykootv
    Jason Weimann - / @unity3dcollege
    Jonas Tyroller - / @jonastyroller
    --------------------------------------------------------------------
    - Website: unitycodemonkey.com/
    - Twitter: / unitycodemonkey
    - Steam: store.steampowered.com/develo...

Комментарии • 454

  • @CodeMonkeyUnity
    @CodeMonkeyUnity  2 года назад +20

    🌍 FREE C# Beginner Complete Course! ruclips.net/video/pReR6Z9rK-o/видео.html
    🔴 Watch my Complete FREE Game Dev Course! 🌍 ruclips.net/video/AmGSEH7QcDg/видео.html
    🌍 HumbleBundle MEGAPACK cmonkey.co/humblebundle
    ✅ Unity Summer Sale (ends soon) assetstore.unity.com/?aid=1101l96nj&pubref=notpublic
    🌍 Get my Complete Courses! ✅ unitycodemonkey.com/courses
    👍 Learn to make awesome games step-by-step from start to finish.

    • @Sir_Isaac_Newton_
      @Sir_Isaac_Newton_ 2 года назад

      I really can't watch the video with its white theme.

    • @Veyron104
      @Veyron104 2 года назад

      Я новичёк: Ненавижу приватные переменные. Целую гору кода писать для того, чтобы достать информацию из этой переменной или её туда записать. Кодеры странные люди: могут продумать весь функционал программы, что на какие классы разбить и какой функционал должен быть у этих классов, но не могут запомнить что player.speed = 10 это изменение скорости персонажа, а не чтение? Уверен, что видео должно называться: Why you should NOT make EVERYTHING poblic! Вам нужно посмотреть фильм "Yes Man". Сначала ты используешь "public" везде, потом тебе говорят что это плохо, и ты везде используешь "private", а потом понимаешь, что там где нужно закрыть переменную, и подписать на изменение этой переменной какое-то событие, то используешь "private", а во всех остальных случаях "public"

  • @Falesam
    @Falesam 2 года назад +194

    In my 4 years of code learning, the public variables become 20% more private each year. I am still lazy about making all private even in cases that I know it should be. But I will get there. Thank you so much for the great videos.

    • @CodeMonkeyUnity
      @CodeMonkeyUnity  2 года назад +39

      The goal is to constantly improve over time so it sounds like you're on the right track!

    • @--.--
      @--.-- 2 года назад +6

      4 years were thrown into the trash. How lazy you must be so that you don't want to think for at least 3 seconds about whether you need to give the variable public access. I'm not even talking about the SerializeField attribute. If you're not going to work and you make games only as an indie developer, then okay. But anyway you didn't have «code learning», you didn't learn how to code.

    • @Daniel-dk6xd
      @Daniel-dk6xd 2 года назад +38

      You got to all riled up about the dude leaving public variables, but I worked in a big tech company and you can't imagine how many big programmers (seniors, 15+ years xp) working in huge application projects just leave public variables left and right. It is a bad practice and doubles the workload sure. But it's not a mortal sin. Relax man, you sound stressed.

    • @aylanj123
      @aylanj123 2 года назад +18

      @@--.-- Dude that was too harsh, relax. Even people with tons of experience sometimes leave public variables thinking it will be needed that way in the future, and just forget about them past the time. It's a bad practice but no one is going to die due to that, just more workload.

    • @snesmocha
      @snesmocha 2 года назад

      @@--.-- Jesus Christ m8, no need to be so harsh. If you didn’t know about it then there’s no need to be so harsh. They aren’t showing an ego and they aren’t Being an ass about it so no need to be an ass

  • @freezinfire
    @freezinfire 2 года назад +34

    I did wonder about this when I started learning coding, never knew why until now. Thank you for the knowledge.

  • @ivopfaffen
    @ivopfaffen 2 года назад +38

    Amazing video! It'd be really cool if you turned this into a series about good coding principles for Unity :)

  • @esosek
    @esosek 2 года назад +47

    Hey Monkey,
    this video should naturally continue with using a property for public reading but private writing and also you should check out the benefits of using scriptable objects as variables because it avoids dependencies and unnecessary errors. I admire what you do for the community! Cheers!

    • @JW-uu9je
      @JW-uu9je Год назад +1

      Events are also good for reducing dependencies but it becomes ever more important to have good documentation as you may not receive errors in the console when things are not working properly.

  • @ahmadel-baher2779
    @ahmadel-baher2779 2 года назад +5

    The best example I've come across as to why you should make fields private and use functions to access them is to think of it like a device such as a TV remote.
    Do you need to know how a remote works in order to use it? Nope. As long as you have the buttons needed to perform its function, that's all that matters. In fact, if late at night a bunch of garden gnomes sneak into your house, and completely change the inner-workings of the remote and then leave - if the next time you use it and it still functions the same, you won't notice the difference.
    In a similar manner, the public entities of a class are those "buttons", and other classes should use those without having to "know" how they are defined as long as the expected result is achieved. You should make it in a way such that you can change the way your class works without affecting code in other classes.

  • @KineticCode
    @KineticCode 2 года назад +5

    Got the megapack, very glad I could find a way to support your channel. You make much better tutorials than anyone else I've seen, and I direct aspiring Unity developers to you whenever I can. A big thanks for all the informative videos you've made, I will always be a silent supporter of your channel.

    • @CodeMonkeyUnity
      @CodeMonkeyUnity  2 года назад +2

      Many thanks! I hope you put those assets to good use!

  • @glorytoukraine429
    @glorytoukraine429 2 года назад +6

    Code Monkey, thank you for keeping and not removing subtitles that are automatically generated by RUclips (even if the speech does not always match what is written in the subtitles). This allows me to translate them into my language (russian) and watch your videos.😜

  • @brocklawson6099
    @brocklawson6099 2 года назад +12

    I just started learning C# for Unity specifically (about a week or so in). The series I've been watching has been great so far but I questioned this the second it was introduced. I absolutely asked myself, "Why would you make anything private ever?" Glad I got my answer, how serendipitous.

  • @davedipy04
    @davedipy04 2 года назад +6

    I dont use unity but to just keep learning about everything makes me happy. I would love to see you make more videos about clean code. Very interesting and helpful

  • @humadi2001
    @humadi2001 2 года назад +8

    Man you are speaking wisdoms in every video you make. Also when you said that the only limitation is the developer experience not Unity, that powerful words convinced me not to distract myself switching between Platforms. Thank you man🌹

  • @thomasremastered6941
    @thomasremastered6941 9 месяцев назад +1

    There is 2 things that I do to make a cleaner code : as you said in the video, I avoid as much as possible the public field, and when I make a public variable or a public function, I also add a comment to clarify the other classes/objects that use this variable/function.

  • @ruliw8520
    @ruliw8520 2 года назад +3

    After remaking my project from scratch and use private most part of the time and not public as i used to do i had the same conclusion of this video, public variables are like those bikes with training wheels, they're great for complete begginers, but as time goes on and things get more complex, the training wheels most part of the time will only limit what experienced people can do instead of helping

  • @Kortonox
    @Kortonox 2 года назад +8

    What I also like about SerielizedField is that you can put further atributes to it, like Range() or Min(). That way you can clamp the value you can give in the editor.

    • @DarthBiomech
      @DarthBiomech 5 месяцев назад

      You just blew my mind. Like, seriously, thank you. I have so many code in OnSerialize() that was there solely for the purpose of me not accidentally setting incorrect value to the variables...

  • @Lonzy
    @Lonzy 2 года назад

    Thank you soo much, I just finished converting all my scripts to Private and Serialized Fields. Feels good having clean code :)

  • @tigransahakyan2840
    @tigransahakyan2840 2 года назад +36

    This HAS TO become a series of clean code principles!

  • @JW-uu9je
    @JW-uu9je Год назад +1

    I recently picked up Code Complete 2 from your video with gamedevtv...I'm really enjoying it! Thank you

    • @CodeMonkeyUnity
      @CodeMonkeyUnity  Год назад

      That's awesome! I hope it helps you just as much as it helped me!

  • @UkranianStallion
    @UkranianStallion 2 года назад +1

    Thanks, as a self taught coder many of this basic concept of OOP alludes me (and i just follow them blindly because of "good practice"), and yes, you're the first one that explains the concept clearly

  • @stephenperry1006
    @stephenperry1006 Год назад +1

    I watched this video shortly after it came out, and after watching your video from yesterday (Difference between Transform & GameObject), I decided to check this out again since you mentioned it. I was curious if everything you said in this video had stuck, and I'm glad to say that it has!
    I realise this is quite basic compared to most other concepts, but even a reminder on "simple" things goes a long way sometimes.
    You're honestly a great teacher, Code Monkey. Thank you for all the amazing content and courses you've made.

    • @CodeMonkeyUnity
      @CodeMonkeyUnity  Год назад

      Thanks! Yup the simple things are sometimes the most important

  • @moheyaldeenalmardiny82
    @moheyaldeenalmardiny82 2 года назад +1

    Amazing video and very important idea
    I wish we could see a series from this kind of videos

  • @clarkmeyer7211
    @clarkmeyer7211 2 года назад +1

    as a beginner I think learning serializefield is super important because of this exact reason. I find it very helpful when applying this to prefabs where you need a different variable in each situation.

  • @sebastianp.332
    @sebastianp.332 2 года назад

    I have made some games before but I still had some doubts regarding why something should be public or private. This is a great explanation, thank you very much!!!

  • @nosh247
    @nosh247 2 года назад

    This is nice! I do it by default, even when I didn't knew why, I really don't like when i bump into some experienced programmer that says, we'll fix it later (making unnecessary public variables for testing) which end up being part of the code and left as public...

  • @dreadzitodev488
    @dreadzitodev488 2 года назад +2

    Pls more Clean Code practices! I love knowing this things

  • @KushagraPratap
    @KushagraPratap 2 года назад

    Your videos give me feeling of a school and teachers teaching like in a session, especially the polls, keep it up

  • @MarushiaDark316
    @MarushiaDark316 2 года назад +4

    I think part of the reason for beginnings to use public for everything is not yet knowing how to make Actions, Events, Accessors, Interfaces, and Constructors work. I would say I'm intermediate level and only just coming to grasp with these myself, but starting to internalize it and using them more and more.

  • @DL-zv5xc
    @DL-zv5xc 2 года назад +2

    Thanks for the book recommendation! I saw this video while I was planning to learn unity, saw the book and decided to wait on watching the rest of the video till I read it. I just reached 6.2, where it talks about this, and so far, this book has taught me a lot! Thanks!

    • @CodeMonkeyUnity
      @CodeMonkeyUnity  2 года назад +1

      It's a great book, I'm glad you're learning a lot from it!

  • @vaflov
    @vaflov 2 года назад +5

    This is quite a contentious topic.
    Making everything private by default is what is thought in schools and is a generally accepted good practice.
    Personally however, I find that non-public access is more trouble than it's worth. Every field, method, class and whatever I write is always public.
    There are several reasons for this.
    First: The language allows you to access private fields anyway, it's called reflection.
    Second: You have to provide access to all your fields anyway (through methods/properties). You may think that you don't have to but if other people end up using your code then someone sometime is going to want to access that private field.
    An example for unity: extending the animator. If you try this you will find that a lot of the fields are non-public, forcing you to use reflection.

    • @oldcat1790
      @oldcat1790 Год назад +2

      Well, that's signs of bad coding practices.
      Reflection for instance is a VERY costly operation that should be used only if you have no other choice, so if you find yourself using it more than a few times then the design of your logic is clearly wrong. Even more so if it used every frame.
      Likewise, it's better to use protected abstract and virtual functions to allow people to write their custom logic via child class if they need to, because it provides even better flexibility at no cost.

    • @yavvivvay
      @yavvivvay Год назад

      @@oldcat1790 it's all fun and games when you call your code from your code. Using other people code, especially old code, especially in ways it was not made to be used makes it a different story. And yes, it is a smell, but it is a better approach to use at most protected so user can do something that is outside your assumptions. Else you need reflection or other such hacks to get what you want.

  • @rezaanataj6978
    @rezaanataj6978 2 года назад

    Thank you for your wide verity types of videos. Your Chanel is the best for learning unity tips and tricks
    I just wanted to know if you have a plan doing a series of videos to cover making textures from beginner to pro as they can be used every where?

  • @r3mus89
    @r3mus89 2 года назад

    great video, thank you! I also like that this way the auto completion stays nice and clean.

  • @RazeVenStudios
    @RazeVenStudios 9 месяцев назад

    Honestly I've struggled so much on this topic. Thank you for the guidance.

  • @bonolenovndongo4557
    @bonolenovndongo4557 2 года назад

    Your tutorials are amazing. Thank you.

  • @progCan
    @progCan Год назад

    very good tutorial, i was always wondering why you make everything serialize field. this explains it very good.

  • @fernandog9647
    @fernandog9647 2 года назад

    really cool video,
    I always had the doubt of how to improve the code and not make everything public, I had heard that it was wrong to use public variables and now I understand why, thank you!

  • @Dritix
    @Dritix 2 года назад +1

    Helpful video, keep it up!

  • @coderanger7708
    @coderanger7708 2 года назад +144

    That light mode IDE offends me

    • @_GhostMiner
      @_GhostMiner 2 года назад +7

      But i guess nobody cares 🤔

    • @raoufbensalem3417
      @raoufbensalem3417 2 года назад +6

      @@_GhostMiner it hurt my eyes

    • @raoufbensalem3417
      @raoufbensalem3417 2 года назад +4

      @@anonymous49125you want to be blind ?

    • @wearwolf4202
      @wearwolf4202 2 года назад +12

      All hail dark mode!

    • @wearwolf4202
      @wearwolf4202 2 года назад +2

      @@raoufbensalem3417 then don't watch. Not everyone likes dark mode

  • @StarkTech47
    @StarkTech47 Год назад +2

    Thank you for this video, you confirmed what I have thought since a long time now. I would be very interested to see you dive deeper into this topic with getter and setter, or juste using function, buff and debuff ... Very good video for an important thing when it comes to make an ambitious game !

    • @CodeMonkeyUnity
      @CodeMonkeyUnity  Год назад +1

      If you want to learn more about clean code I can highly recommend the book Code Complete 2
      And I just recently released my latest course which is heavily focused on writing good clean code to take your skills to the next level ruclips.net/video/QDr_pjzedv0/видео.html

  • @SteveTheExploiter
    @SteveTheExploiter 2 года назад +1

    Thank you! Finally! So many tutorials just toss about the public variables and it's very disappointing. SerializedField is also good for debugging as you can monitor the variable's value in the inspector in real time.

  • @migcreatesgames2622
    @migcreatesgames2622 2 года назад +3

    Great explanation process! I do try to avoid public variables and only using for Game Objects or Transform. You should also do an episode on public static variables. I try as much as I can to stay away from static and rather do properties or pass reference.

    • @migcreatesgames2622
      @migcreatesgames2622 2 года назад

      @@EvitoCruor You can still use the public static classes for example I will use them for an inventory class. The issue comes when you are getting an error when changing a public static variable and forget where the variable and change is coming from. Most of my games have 60 or more scripts : / better than doing one long script

  • @Skyefaux
    @Skyefaux 2 года назад +1

    I would love a video series on general architecture and design patterns and how they are used in game dev

  • @brandenimmerzeel8182
    @brandenimmerzeel8182 2 года назад +1

    Great video! A similar one could be the implications of singletons as I feel like they are something I used to abuse alot in the early days too (and still do when im lazy.)

  • @guridoraccoon6375
    @guridoraccoon6375 2 года назад +1

    Great advice. Thank you so much

  • @richnaisanze
    @richnaisanze 2 года назад +1

    Pleaseeeee keep posting videos about "Clean Code" in Unity, I'm very interested about clean code, Thank youuu!

  • @brellos7220
    @brellos7220 6 месяцев назад

    Great video!!! It's really helpful.

  • @nilsleonhardtdev
    @nilsleonhardtdev 2 года назад

    Very good tip, imma use it from now on!

  • @GrantCarvalho
    @GrantCarvalho 2 года назад

    I enjoyed and learned so much from your videos, Code Monkey! I went ahead and bought your course on Udemy. Thank you!

  • @mehmedcavas3069
    @mehmedcavas3069 2 года назад +18

    I haven't used public variables for almost 2 years. If I have to access the variable I create a property like public float Speed => speed; so they can access it but can't change it. for changing I use methods which is also still a rare case

    • @CodeMonkeyUnity
      @CodeMonkeyUnity  2 года назад +4

      Yup same thing here, I pretty much only use public for singletons and constants.
      public static GameManager Instance { get; private set; }

  • @pixeldust8362
    @pixeldust8362 2 года назад +1

    I think a better way to manage accessibility is with namespacing. Obviously these should be used together for best results

  • @alexanderdorenkamp
    @alexanderdorenkamp 2 года назад +1

    Awesome vid! Can you make more clean code videos?

  • @saito853
    @saito853 2 года назад +1

    if you want to take it to another step, fields should NEVER be public. They should be exposed through properties or methods (just do a quick Google search on Properties vs public fields).
    In C# you can create a public auto properties like this:
    public float Speed { get; set; } //The naming convention for Properties is PascalCase
    However in Unity, public properties will not be exposed in the Inspector, this is because a Property is literally just a layer of abstraction which includes a private backing field and two public methods, you can think of the property I declared above like this:
    private float speed;
    public void SetSpeed{float value} => speed = value;
    public float GetSpeed() => return speed;
    So in order to expose Properties to the inspector, you have to expose the backing field (which is normally hidden if you use auto properties) by using the [field: SerializeField] attribute, which basically tells the compiler to apply [SerializeField] attribute to the backing field of this property.
    [field : SerializeField] public float Speed { get; set; }

  • @vast634
    @vast634 2 года назад +1

    The ominous "accidental modification". There is a cost in hiding access: it create lots of additional boilerplate code for public getters and setters. The cost is a longer time to scroll to the now longer sourcecode, with the programmer having less overview.
    Unless the code is ment for others to use, such as in a library or module, adding lots "security" to the code can have a negative effect. It sufficient to make the interface to that module safe.

    • @sharif47
      @sharif47 2 года назад

      I'm having a feeling that the "accidental modification" part doesn't really change much with private variables and public functions.
      If a script has a variable and a function for changing the variable, then how is it any less troublesome to change it from the function, rather than the variable itself?
      If an error occurs anywhere, this means either the errors are coming from whichever function is accessing it, which was the exact same problem I was having before...
      Or the problem is actually in the function I created, which means there's a new boilerplate code that I'll have to search as well.
      Maybe the new function can also include some code that tells who is calling it, but this code might need to be written off in the end for performance issues.
      The only place where I see are where the function happens to be both complex and general at the same time. For example, when my player dies, the player gameobject disappears along with some extra stuffs to show the player died. If I code all of it newly in every script that can kill me, then it's a lot of code to search for error correction. But if I do one death function to hadle all of it, I can easily check what caused it.
      But for something so small as getting and setting values, this looks redundant to me.

  • @AJ213Probably
    @AJ213Probably 2 года назад

    One thing I like to do is have readonly accessors for my private fields if other classes need that information. So if we have
    private float speed;
    we would also have
    public float Speed => speed;
    so that we can read the speed value but not write it. Also => in this case is the short hand for
    public float Speed { get { return speed; } }
    You can also do this for functions too if it's a single line

  • @JaredKuvent
    @JaredKuvent 2 года назад +4

    I'm just starting out with C#, but not unfamiliar with some scripting. Regarding beginner's tutorials teaching to use Public fields: wouldn't it be better to teach the best practice early on? I know it could be a rabbithole of theory before practice, but as a new developer, it can be confusing to learn one way and then discover I should be doing it differently.
    As I was told when learning piano, "practicing with the wrong technique will only make the learning harder in the long run."
    However, maybe the important thing is to just jump in, without too much theory, since taking the initial plunge is often the most difficult.

    • @vatyunga
      @vatyunga 2 года назад

      yes it would be better

  • @lasttrump6015
    @lasttrump6015 9 месяцев назад

    Interesting but I found making everything public helped me in my coding a lot. I just have a strict rule never to update a public variable in more then one spot and all the code can read it but only updated in one place, so if other things needed to influence it then create new variable for that and still update the main variable in the one place with those adjustments if needed. I also of course use longer and more detailed variable names to reduce conflicts and also a full list of all used variables in a table I can check is not already used elsewhere....not hard and solved a lot of conflict problems that way. The full variable table was good to also sort between what needs to be saved in the game save state and what is not needed.
    I also have tended towards functional programming which allows local variables that are not global by default anyway (unless I want them to) so also helps a lot in avoiding conflicts.

  • @alexgeeves7096
    @alexgeeves7096 2 года назад +1

    Thanks dude! I'm exactly your target audience for this video and I appreciate it a lot

    • @CodeMonkeyUnity
      @CodeMonkeyUnity  2 года назад +2

      I'm glad you found the video and I'm glad you liked it! Thanks!

  • @IngoLingoAnimations
    @IngoLingoAnimations 2 года назад +9

    I like learning the "why" to certain aspects of coding.

  • @B4NTO
    @B4NTO 2 года назад +1

    Great vid thanks :)

  • @Soloman274
    @Soloman274 2 года назад +3

    More Clean Code principles in Unity context! ❤️

  • @sharif47
    @sharif47 2 года назад +1

    And here I was expecting you to talk about why going public (as Unity did some time ago) was a bad idea.

  • @aaronedvalson104
    @aaronedvalson104 2 года назад +1

    I used to just shrug it off and do it my way, with everything public. Once I got a big enough project, I realized a few of the reasons we shouldn't make everything public. Now, I actually try to anticipate how exposed it'll need to be, and work from private to public.

  • @Aidan-dc3zr
    @Aidan-dc3zr 2 года назад +1

    I personally prefer to keep things as protected rather than private because it's pretty much the same as private except it makes code written more expandable later on without changing anything.

  • @arkfish
    @arkfish 2 года назад

    Exactly. Code that is only used internally by one class can be private, there's no harm in doing so, and it will benefit you in the long-term. Unnecessarily publicizing everything will also make your properties explorer a lot more cluttered, since now if you want to edit a variable you're going to have to search through a lot of other variables.
    I'd only publicize fields if I need to for debug purposes or to tweak values without recompiling every time I change it

  • @philipkaltsounis8097
    @philipkaltsounis8097 2 года назад

    You can also make a variable with a public get and private set. That way other classes can check the value of the variable but it cannot be modified

    • @CodeMonkeyUnity
      @CodeMonkeyUnity  2 года назад

      That would be a property, not a variable, and yes properties can indeed be used for validation and limiting get/set

  • @buddyroach
    @buddyroach 2 года назад +1

    btw, that public variable you made called `speed` cant be used by other scripts THAT easily. You have to call the script in order to call it's public variables so Idky people act like its the other way around.

  • @REOsama
    @REOsama Год назад +1

    This is literally the best explanation

  • @wise_old_tree
    @wise_old_tree 2 года назад

    Thank you!!!!

  • @jamesmillerjo
    @jamesmillerjo 2 года назад

    Nice step-by-step OO lecture

  • @jean-michel.houbre
    @jean-michel.houbre 2 года назад +1

    Well explained. Why did you change the recommended book? It seems to me that in your video on how to become a developer, you recommend "Clean Code: A Handbook of Agile Software Craftsmanship (Robert C. Martin Series)" ?

    • @CodeMonkeyUnity
      @CodeMonkeyUnity  2 года назад +2

      Both are great and both cover the same topic. Code Complete is a lot more thorough at 900 pages whereas Clean Code is much more concise.
      So to get a base understanding of clean code principles, maybe start with Clean Code first.
      To get a thorough understanding of every specific element that makes good code, go with Code Complete.
      Or really the best of all just get both!

  • @xwestlightx
    @xwestlightx 11 месяцев назад

    i justt started learning with Unity. after this video im wondering why i would ever use the public version now instead of a Serializedfield?
    should i avoid this completly or are there some circumstances where the public version still makes more sense to use?
    thanks for the great videos btw.! im learning alot from you!

  • @royorgames771
    @royorgames771 2 года назад

    Really good points. Do you have a good solution, when unit testing the classes? Normally I would use the constructor to set private fields, however we do not have a constructor when using monoBehaviours =( I have used a Initialize method as a constructor in the tests, but I am not quite happy with that solution.

    • @CodeMonkeyUnity
      @CodeMonkeyUnity  2 года назад

      Yeah Unit Testing MonoBehaviours is very tricky, I think the best approach is to keep all your testable logic in normal C# classes and only use the MonoBehaviours to call the Update();

  • @CodemasterJamal
    @CodemasterJamal 2 года назад

    I actually start off making all of my variables private but, then change them if they NEED to be accessed from other classes.

  • @FM_GOBi
    @FM_GOBi 2 года назад +1

    Hey Code Monkey, have you written unit tests for your games?
    Do you have plans on covering that as a tut perhaps?

    • @CodeMonkeyUnity
      @CodeMonkeyUnity  2 года назад

      I don't normally do unit tests for my games since I have to work insanely fast in order to find success with those games, but I am constantly trying to write code that could be testable.
      So I'm constantly thinking about how to minimize dependencies and make every script as standalone as possible.
      Unity does have a bunch of Unit Testing tools which I've never used but I'd love to research them when I have the time.

  • @FeedMyKids1
    @FeedMyKids1 2 года назад +1

    Code Complete is the BEST book I've ever read.

  • @RazeVenStudios
    @RazeVenStudios 9 месяцев назад

    Question. So if we make functions like for the enemy, and UI, and enemy boss to change speed, how would we change the speed when speed is private? If we make a public function but use a private variable how would the variable change?

    • @CodeMonkeyUnity
      @CodeMonkeyUnity  9 месяцев назад +1

      Not sure what you mean, you make the function public which means any class can call that function, then inside that function you can modify any private variables.
      You don't need variables used in a public function to also be public

    • @RazeVenStudios
      @RazeVenStudios 9 месяцев назад

      Ok that makes sense thank you@@CodeMonkeyUnity

  • @williamjay2386
    @williamjay2386 2 года назад

    Great video. But I have a question, do you have a video about inheritance and sub-classes in C#? I know that using those helps with clean code, but I have a hard time finding concrete examples in game development.

    • @CodeMonkeyUnity
      @CodeMonkeyUnity  2 года назад +1

      I usually avoid inheritance, I find they always cause more problems than they help.

  • @Drillgon
    @Drillgon 2 года назад

    I thought you meant open source by public at first and it took me a whole minute to realize that "public" meant the access modifier.

  • @ThatOneRobloxDev
    @ThatOneRobloxDev 8 месяцев назад

    You could also make variables public and use the "HideInInspector" attribute to hide it in the inspector.

    • @CodeMonkeyUnity
      @CodeMonkeyUnity  8 месяцев назад

      That would indeed hide it in the inspector but it would not protect the variable from being modified by any other class in your entire codebase

    • @ThatOneRobloxDev
      @ThatOneRobloxDev 8 месяцев назад

      ​@@CodeMonkeyUnity But in a scenario where you have a variable that you want to not be visible in the inspector, but still be modified in any other class... then using this attribute is useful. Basically being the inverse of SerializeField where you want a variable that is not modifiable by other class, but shown in the inspector.

  • @unofficialSummer
    @unofficialSummer 2 года назад

    I saw the thumb and thought that it was gonna be a video about LIFE lol, no problem though, keep it up

  • @grazeen
    @grazeen 2 года назад

    Hi, I am following your videos for a while now.
    I have a friend who is deaf and watching your videos, i sometimes explain him what are you talking about and what are you saying(auto subtitles are messy).
    So if you open subtitle adding feature i will be happy to help adding subtitles.
    Thanks in advance. Keep up good work :)

    • @CodeMonkeyUnity
      @CodeMonkeyUnity  2 года назад

      RUclips disabled community subtitles a while ago, it's no longer something that can be done, there's only the auto generated ones.

  • @arcday4281
    @arcday4281 2 года назад

    Useful for beginners ! But following carefully any of your videos related to the code, you can instantly learn how to write clean code )))

  • @miz0n3-
    @miz0n3- 2 года назад +1

    Just asking : How did you started your game development career? I mean what kind of game engine you used and programming language as well. Just want to know, to have a basic idea. Iam currently having a hard time in using unity. Specially at coding but I love to code and want to do so. Your channel helps a lot to fix them.
    Thanks for your support through videos. ❤️

    • @CodeMonkeyUnity
      @CodeMonkeyUnity  2 года назад +1

      I covered my game dev journey here ruclips.net/video/0zscPf_U1VY/видео.html
      Basically I started making IRC scripts, then moved onto Flash and finally when I wanted to make PC games I found Unity and I've been using it ever since.

  • @jackoberto01
    @jackoberto01 2 года назад

    The only time I've really needed public fields is when creating ScriptableObjects from editor scripts and need to set the values when for example generating items
    It's a bit unfortunate that I have to do it like this if it was in C++ you could make the editor for it a friend
    The C# solutions are all a bit iffy however like putting the editor logic inside the actual ScriptableObject class inside of a #if UNITY_EDITOR
    Having a Setup() method that takes all the fields as parameters
    Using reflection to set the private fields

  • @scrillagorilla4524
    @scrillagorilla4524 6 месяцев назад

    love your videos bro. some day soon when i get a job in the field i'll donate. thank you

    • @CodeMonkeyUnity
      @CodeMonkeyUnity  6 месяцев назад

      Best of luck in your learning journey!

  • @reynoldcracker02
    @reynoldcracker02 2 года назад

    I almost never make it public unless necessary. And when I need to reference a variable from Unity I just marked them as Serializable Field while keeping them private. But I am curious of why not just make everything public xD.

  • @odo432
    @odo432 2 года назад

    So many tutorials use Public variables and it's something that has always annoyed me. Unless you require external access, just make everything private. And a lot of the time if you require external access you can make use of get/set and have much greater control over access (eg make getting the variable public but setting it private etc). And if you need access to private variables via Unity then use [Serializefield] attribute.

  • @megasoniczxx
    @megasoniczxx 2 года назад

    So in my case, i'm trying to make a racing game but have two separate scripts that handle the acceleration and steering of the car and I have code attached to this that decreases the speed of the car by a certain amount when turning. I do this by making a variable for the acceleration script and then modifying the speed variable whenever the player turns (the speed variable itself is public since I can't get access otherwise). I'm still relatively new with programming even though i've been doing it on and off for the past few years so this may seem like a dumb question, but is there a more efficient way that I should be doing this instead of making the speed variable public?

  • @waguno
    @waguno 2 года назад

    A must watch vídeo

  • @404waffles
    @404waffles 2 года назад

    im not even in gamedev and this is pretty useful

  • @Bonnie39
    @Bonnie39 2 года назад

    This is good to know as a beginner programmer :)

  • @kerhabplays
    @kerhabplays Год назад

    Hey Code Monkey , Thanks for the series c# tutorials ..But I have a question, For example you say that instead of using Public it's better to use serialized field to have a clean code , so how can I edit that variable in other classes if I want to? without changing it to public...or I can't?

    • @CodeMonkeyUnity
      @CodeMonkeyUnity  Год назад +1

      You keep the field private and expose some public function to change the field in some way. That way you can add all kinds of validation in that function or perhaps fire an event or do some math before setting the underlying field.

    • @kerhabplays
      @kerhabplays Год назад

      @@CodeMonkeyUnity oh yeah! Tnx

  • @lennyseed9255
    @lennyseed9255 2 года назад

    The problem that I face while keeping as much as possible private is that I just dont understand on how to reference something private in one script from another script. It sometimes not work for me even if I copy directly from someone else's scripts

  • @heandog6481
    @heandog6481 2 года назад +1

    Hey I’m pretty new to coding in c# for unity. Can you give an example of a function that could call a private serialized variable?

  • @bladonski
    @bladonski 2 года назад

    Never seen your channel before and thought you were gonna be talking against open sourcing applications lol

  • @misterrhombus
    @misterrhombus Год назад +1

    How would you go about changing a private variable from another script? Like the SetSpeed() you mentioned? Won't public functions make your code less scaleable (I could be misunderstanding something)?

    • @CodeMonkeyUnity
      @CodeMonkeyUnity  Год назад +1

      Yes exactly, "less scalable" can also be described as "less accessible" which is exactly the point, you want to limit access as much as possible to limit how many possible things can go wrong. It's much easier to find references of all SetSpeed(); function calls than all read/write direct access to the variable itself.

  • @hoseinstar9661
    @hoseinstar9661 2 года назад +1

    Tnx 🌷🙏 really good,

  • @efs515
    @efs515 2 года назад

    I’ve been wondering about this for a while and never heard an answer that made sense till this video! Thank youuu!!
    I have 2 questions if I may,
    1. What is a very good reason for public variables?
    2. I’ve seen people use get + set to work around private variables. Looks like the same thing as making it public. Is there a good reason for using this?

    • @BlackHayateMX
      @BlackHayateMX 2 года назад +2

      1. Usually when you're debugging or it's a very safe variable that you can be extremely sure you control
      2. Using a set+get allows for extra validation/formatting, for example, you can make a set that takes a string "2" and casts it into a number, and if the string is not a number, fill it with either a default value or not change the variable at all. Basically, it's a failsafe. Same for get, you can store your variable as an integer (saving memory) but when you GET it, return it as a string, an object, a json, etc.

    • @efs515
      @efs515 2 года назад

      @@BlackHayateMX ah I see! So set+get is handy to add some extra functionality. But if left plain, then there’s really no use for it?
      Thanks for your reply! :)

    • @BlackHayateMX
      @BlackHayateMX 2 года назад +1

      @@efs515 correct!

    • @efs515
      @efs515 2 года назад

      @@lekretka ah thats a great point! thank you!

  • @ChillinGames
    @ChillinGames 2 года назад

    another tip is if you want a field to be public but you DONT want to add it to the growing mess on the editor, make it internal.

    • @CodeMonkeyUnity
      @CodeMonkeyUnity  2 года назад

      For that you can also use the attribute [HideInInspector]

  • @lee1davis1
    @lee1davis1 2 года назад

    Off subject. How do you handle accounting regarding patron and sales of your game? Do you have accounting experience or do you hire an accountant?

    • @CodeMonkeyUnity
      @CodeMonkeyUnity  2 года назад

      I have an accountant but I also set up Patreon with the tier where they handle all the VAT stuff, so I just need to create an invoice.

  • @Only4GamersXyz
    @Only4GamersXyz 2 года назад +1

    Hello,
    Is there any difference between
    float speed;
    vs
    private float speed;
    should I always use private?

    • @CodeMonkeyUnity
      @CodeMonkeyUnity  2 года назад +1

      Some compilers default to private, others to protected.
      On a class hiding it might make it private, on an interface it will make it public.
      So it's always best to be clear and specify exactly what accessibility you want.

    • @Only4GamersXyz
      @Only4GamersXyz 2 года назад

      @@CodeMonkeyUnity Thanks for the reply. What is default in unity?

  • @seppukun208
    @seppukun208 2 года назад +1

    I’ve always used serialised field ever since I learnt about them like a month or 2 into first learning unity. That’s the whole point of encapsulation right?

    • @TheExiledMeriler
      @TheExiledMeriler 2 года назад

      Thats the point of one of the parts of encapsulation to be exact.