Why you should NOT make everything PUBLIC!

Поділитися
Вставка
  • Опубліковано 7 лют 2025
  • 🌍 FREE C# Beginner Complete Course! • Learn C# Beginner FREE...
    🔴 Watch my Complete FREE Game Dev Course! 🌍 • Learn Unity Beginner/I...
    🌍 HumbleBundle MEGAPACK cmonkey.co/hum...
    ✅ Unity Summer Sale (ends soon) assetstore.uni...
    🌍 Get my Complete Courses! ✅ unitycodemonke...
    👍 Learn to make awesome games step-by-step from start to finish.
    🎮 Get my Steam Games unitycodemonke...
    💬 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! ✅ unitycodemonke...
    👍 Learn to make awesome games step-by-step from start to finish.
    🌍 Get Code Monkey on Steam!
    👍 Interactive Tutorials, Complete Games and More!
    ✅ store.steampow...
    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 unitycodemonke...
    📝 Get the Code Monkey Utilities at unitycodemonke...
    #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: unitycodemonke...
    Twitter: / unitycodemonkey
    Steam: store.steampow...

КОМЕНТАРІ •

  • @CodeMonkeyUnity
    @CodeMonkeyUnity  3 роки тому +20

    🌍 FREE C# Beginner Complete Course! ua-cam.com/video/pReR6Z9rK-o/v-deo.html
    🔴 Watch my Complete FREE Game Dev Course! 🌍 ua-cam.com/video/AmGSEH7QcDg/v-deo.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_ 3 роки тому

      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 3 роки тому +198

    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  3 роки тому +40

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

    • @eloreneloreneloreneloreneloren
      @eloreneloreneloreneloreneloren 3 роки тому +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 3 роки тому +39

      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 3 роки тому +18

      @@eloreneloreneloreneloreneloren 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 3 роки тому

      @@eloreneloreneloreneloreneloren 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 3 роки тому +34

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

  • @esosek
    @esosek 3 роки тому +46

    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 2 роки тому +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.

  • @KineticCode
    @KineticCode 3 роки тому +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  3 роки тому +2

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

  • @ivopfaffen
    @ivopfaffen 3 роки тому +37

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

  • @trader_iks
    @trader_iks 3 роки тому +6

    Code Monkey, thank you for keeping and not removing subtitles that are automatically generated by UA-cam (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.😜

  • @stephenperry1006
    @stephenperry1006 2 роки тому +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  2 роки тому

      Thanks! Yup the simple things are sometimes the most important

  • @ahmadel-baher2779
    @ahmadel-baher2779 3 роки тому +6

    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.

  • @JW-uu9je
    @JW-uu9je 2 роки тому +1

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

    • @CodeMonkeyUnity
      @CodeMonkeyUnity  2 роки тому

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

  • @KnoxxyPoxxy
    @KnoxxyPoxxy 3 роки тому +9

    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 Рік тому

      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...

  • @davedipy04
    @davedipy04 3 роки тому +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

  • @Lonzy
    @Lonzy 2 роки тому

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

  • @alexgeeves7096
    @alexgeeves7096 3 роки тому +1

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

    • @CodeMonkeyUnity
      @CodeMonkeyUnity  3 роки тому +2

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

  • @brocklawson6099
    @brocklawson6099 3 роки тому +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.

  • @thomasremastered6941
    @thomasremastered6941 Рік тому +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.

  • @RobertGuilman
    @RobertGuilman 3 роки тому +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

  • @tigransahakyan2840
    @tigransahakyan2840 3 роки тому +38

    This HAS TO become a series of clean code principles!

  • @humadi2001
    @humadi2001 3 роки тому +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🌹

  • @RazeVenStudios
    @RazeVenStudios Рік тому

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

  • @saito853
    @saito853 3 роки тому +2

    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; }

  • @sebastianp.332
    @sebastianp.332 3 роки тому

    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!!!

  • @fernandog9647
    @fernandog9647 3 роки тому

    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!

  • @dreadzitodev488
    @dreadzitodev488 3 роки тому +2

    Pls more Clean Code practices! I love knowing this things

  • @clarkmeyer7211
    @clarkmeyer7211 3 роки тому +2

    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.

  • @StarkTech47
    @StarkTech47 2 роки тому +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  2 роки тому +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 ua-cam.com/video/QDr_pjzedv0/v-deo.html

  • @progCan
    @progCan 2 роки тому

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

  • @moheyaldeenalmardiny82
    @moheyaldeenalmardiny82 3 роки тому +1

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

  • @vaflov
    @vaflov 3 роки тому +6

    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 роки тому +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 2 роки тому

      @@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.

  • @KushagraPratap
    @KushagraPratap 3 роки тому

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

  • @MarushiaDark316
    @MarushiaDark316 3 роки тому +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.

  • @GrantCarvalho
    @GrantCarvalho 3 роки тому

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

  • @ruliw8520
    @ruliw8520 3 роки тому +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

  • @SteveTheExploiter
    @SteveTheExploiter 3 роки тому +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.

  • @sharif47
    @sharif47 3 роки тому +1

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

  • @AJ213Probably
    @AJ213Probably 3 роки тому

    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

  • @nosh247
    @nosh247 3 роки тому

    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...

  • @bonolenovndongo4557
    @bonolenovndongo4557 3 роки тому

    Your tutorials are amazing. Thank you.

  • @Dritix
    @Dritix 3 роки тому +1

    Helpful video, keep it up!

  • @r3mus89
    @r3mus89 3 роки тому

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

  • @richnaisanze
    @richnaisanze 3 роки тому +1

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

  • @migcreatesgames2622
    @migcreatesgames2622 3 роки тому +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 3 роки тому

      @@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 3 роки тому +1

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

  • @iSTOR
    @iSTOR 6 місяців тому

    C# allows you to define getters and setters that allows to control and access directly to public variables but read and writing will be performed thru getters and setters. That makes obsolete the must-to-be-private members with manually defined getters/setters.

    • @CodeMonkeyUnity
      @CodeMonkeyUnity  6 місяців тому

      Sure you can use properties instead of get/set functions, but you still need SerializseField to expose it in the editor

    • @iSTOR
      @iSTOR 6 місяців тому

      @@CodeMonkeyUnity the point is that using private properties has not advantages over public ones once you can define implicit hidden getters/setters to handle reads/writes to those public properties... no advantages in using privates and all problems and all overhead... I prefer to use private properties only for... really private things that are used in code internals, whose are usually not serializalbe and of course never exposed to the inspector (they are private!!! inspector is the more public-like-thing... making a private property visible for the inspector is like making it super-public).

  • @coderanger7708
    @coderanger7708 3 роки тому +148

    That light mode IDE offends me

    • @_GhostMiner
      @_GhostMiner 3 роки тому +7

      But i guess nobody cares 🤔

    • @raoufbensalem3417
      @raoufbensalem3417 3 роки тому +6

      @@_GhostMiner it hurt my eyes

    • @raoufbensalem3417
      @raoufbensalem3417 3 роки тому +4

      @@anonymous49125you want to be blind ?

    • @wearwolf4202
      @wearwolf4202 3 роки тому +12

      All hail dark mode!

    • @wearwolf4202
      @wearwolf4202 3 роки тому +2

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

  • @brandenimmerzeel8182
    @brandenimmerzeel8182 3 роки тому +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.)

  • @REOsama
    @REOsama Рік тому +1

    This is literally the best explanation

  • @nilsleonhardt
    @nilsleonhardt 3 роки тому

    Very good tip, imma use it from now on!

  • @arcday4281
    @arcday4281 3 роки тому

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

  • @arkfish
    @arkfish 3 роки тому

    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

  • @alexanderdorenkamp
    @alexanderdorenkamp 3 роки тому +1

    Awesome vid! Can you make more clean code videos?

  • @pixeldustinteractive
    @pixeldustinteractive 3 роки тому +1

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

  • @unofficialSummer
    @unofficialSummer 3 роки тому

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

  • @brellos7220
    @brellos7220 Рік тому

    Great video!!! It's really helpful.

  • @vast634
    @vast634 3 роки тому +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 3 роки тому

      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.

  • @willpetillo1189
    @willpetillo1189 3 роки тому +10

    This is great advice for beginners moving up to the intermediate level, but I have found that, in moving from the intermediate to advanced level, making things public is almost universally better--though the reasons are nuanced, address long-range issues, and assume some things.
    The problem with private variables arises when one transitions from writing game logic to tool logic (which is then assembled into game mechanics by juniors or non-programmers). At that point, the logic "only make something public if it has a clear reason to be public" breaks down because you can't possibly know the full range of use-cases in advance and so to lock something down imposes a permanent design limitation based on a lack of imagination. As a specific example, when working with Mecanim, one must maintain a code-based state machine to control characters with animation in addition to the animator state machine and keep both in sync with each other (or work around the system entirely with animator.Play("magicString")...all because someone at Unity couldn't think of a reason to access animation states other than the one currently playing and made that information private.
    This may sound like an edge case, but over the years, I have lost weeks if not months worth of development time working around tools that have made things private that I needed to access for some reason, and 0.0 seconds debugging problems that arose because something was public that should have been private. Further, in my own programming, I have recently been leaning heavily on a nested composition pattern, where every piece of code has the potential to become a building block for code that operates on a higher level of abstraction, and in that context it is often useful to change settings externally via OnValidate.
    Another, more nuisance-level problem is what I call "fake encapsulation". For example, this disturbingly-common nonsense:
    private myVariable;
    public MyVariable { get => myVariable; set => myVariable = value; }
    Assuming the above is not to complete an interface, the above pattern adds negative value. In addition to wasting space, it also creates the illusion that myVariable is protected from access from the outside, when in reality it does literally nothing other than require using a capital 'M' to access it.
    Now, I am making a couple of assumptions that mitigate the benefits of private variables/methods. First, I am assuming one has an IDE with right-click -> find all instances. Second, I am assuming that every...single...time one modifies a variable, especially one in a different script, one does so with a knowledge of the impact of changing that variable and the alternative ways of accomplishing the same goal (as opposed to just looking for something quick that "works"). I take it as an axiom that if new code breaks something, it is ALWAYS the fault of the new, accessing code, and NEVER the fault of the old code not putting up sufficient guard rails. And if the goal is communicating intent, that's what comments are for. By analogy, if a neighbor breaks into my house and steals my computer, the neighbor is to blame for the loss, not me for having insufficient security.
    Granted, being mindful about how variables are set is certainly good practice. For example, calling a Damage(int value) function instead of directly decreasing health is probably a good idea. This, however, is not for the sake of "protecting" the health state, but for the sake of readability, since damage is the concept being implemented and it just happens to result in decreasing health (possibly among other things).

    • @fuuuuuuuuuuuuuuuuuuuuuuuuu
      @fuuuuuuuuuuuuuuuuuuuuuuuuu 2 роки тому

      Thank you. #vindicated

    • @oldcat1790
      @oldcat1790 2 роки тому

      Calling a Damage(int value) function is not for the sake of "protecting" the health state, but for the sake of keeping an eye on health changes. During debugging you can easily add debug.log into such function, unlike direct changes.

    • @willpetillo1189
      @willpetillo1189 2 роки тому

      As I said, treating Damage() as a process that happens to involve decreasing health rather than directly accessing the variable makes sense.
      And yes, having the potential to easily add debugging logic is one benefit of this process framing. That said, in a context where debugging is the only additional consideration--that is, when it actually makes sense to modify the variable directly because that is a better analogy for what is happening than a process--you could do so with setter logic.
      In any case, my point stands: whenever anyone actually argues that variables should not be public, the stated reason is pretty much always for the sake of "protecting" state, I'm inclined to take them at their word, and I don't consider this a valid reason.

  • @Soloman274
    @Soloman274 3 роки тому +3

    More Clean Code principles in Unity context! ❤️

  • @philipkaltsounis8097
    @philipkaltsounis8097 3 роки тому

    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  3 роки тому

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

  • @guridoraccoon6375
    @guridoraccoon6375 3 роки тому +1

    Great advice. Thank you so much

  • @rezaanataj6978
    @rezaanataj6978 3 роки тому

    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?

  • @lasttrump6015
    @lasttrump6015 Рік тому

    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.

  • @B4NTO
    @B4NTO 3 роки тому +1

    Great vid thanks :)

  • @IngoLingoAnimations
    @IngoLingoAnimations 3 роки тому +8

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

  • @JaredKuvent
    @JaredKuvent 3 роки тому +2

    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.

  • @Aidan-dc3zr
    @Aidan-dc3zr 3 роки тому +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.

  • @JW-uu9je
    @JW-uu9je 2 роки тому

    also what you say from 6:00 - 6:40 is excellent!!!

  • @Drillgon
    @Drillgon 3 роки тому

    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.

  • @mehmedcavas3069
    @mehmedcavas3069 3 роки тому +17

    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  3 роки тому +4

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

  • @marksmithcollins
    @marksmithcollins 3 роки тому

    Nice step-by-step OO lecture

  • @buddyroach
    @buddyroach 3 роки тому +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.

  • @scrillagorilla4524
    @scrillagorilla4524 Рік тому

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

  • @aaronedvalson104
    @aaronedvalson104 3 роки тому +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.

  • @alejandroalzatesanchez
    @alejandroalzatesanchez 3 роки тому

    The title sounds like privacy informative video
    That's is .POG.

  • @ChillinGames
    @ChillinGames 3 роки тому

    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  3 роки тому

      For that you can also use the attribute [HideInInspector]

  • @lennyseed9255
    @lennyseed9255 3 роки тому

    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

  • @404waffles
    @404waffles 3 роки тому

    im not even in gamedev and this is pretty useful

  • @grazeen
    @grazeen 3 роки тому

    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  3 роки тому

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

  • @hoseinstar9661
    @hoseinstar9661 2 роки тому +1

    Tnx 🌷🙏 really good,

  • @CodemasterJamal
    @CodemasterJamal 3 роки тому

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

  • @odo432
    @odo432 3 роки тому

    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.

  • @ThatOneRobloxDev
    @ThatOneRobloxDev Рік тому

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

    • @CodeMonkeyUnity
      @CodeMonkeyUnity  Рік тому

      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 Рік тому

      ​@@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.

  • @badendhappy2903
    @badendhappy2903 3 роки тому

    *Me looking at my coworkers that makes ALL variables public*

  • @bronsk3809
    @bronsk3809 3 роки тому

    Great video...cool thing (coming from an Game Engineering Student second year)

  • @waguno
    @waguno 3 роки тому

    A must watch vídeo

  • @FM_GOBi
    @FM_GOBi 3 роки тому +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  3 роки тому

      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.

  • @BreadAckerman
    @BreadAckerman 2 роки тому +1

    Now i have knowledge. Bye gotta go and change every variable to sterelized private

  • @bladonski
    @bladonski 3 роки тому

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

  • @deadyanothaikiropool1chait713
    @deadyanothaikiropool1chait713 3 роки тому

    Soooo that's why some people make the long getter and setter function

  • @honeybeela1111
    @honeybeela1111 3 роки тому

    Damn yes yes yes I started doing this a while back and I maybe use a public variable like once a week

  • @Bonnie39
    @Bonnie39 3 роки тому

    This is good to know as a beginner programmer :)

  • @jackoberto01
    @jackoberto01 3 роки тому

    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

  • @kitsunedotexe3587
    @kitsunedotexe3587 3 роки тому

    beginner here, thank you!

  • @lovegeneration8464
    @lovegeneration8464 3 роки тому

    Make more videos like this please.

  • @nogamesnofame
    @nogamesnofame 3 роки тому

    I legit used this method on my first class of combined programming(work in a group to make a game), but it was disliked by my fellow students due to being slightly more complex than leaving stuff public...

  • @wise_old_tree
    @wise_old_tree 3 роки тому

    Thank you!!!!

  • @XcutAngel
    @XcutAngel 3 роки тому

    I was waiting for something regarding performance. Phew 😅...

  • @Only4GamersXyz
    @Only4GamersXyz 3 роки тому +1

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

    • @CodeMonkeyUnity
      @CodeMonkeyUnity  3 роки тому +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 3 роки тому

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

  • @reynoldcracker02
    @reynoldcracker02 3 роки тому

    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.

  • @lpnp9477
    @lpnp9477 3 роки тому

    I'm of the mind that you should tend toward protected rather than private. Nothing worse then inheriting a class and needing to change one small thing but you can't because developers are obsessed with making things private. Then you have to duplicate code to achieve what you want because you're not allowed to edit the original source.
    This happens to me more often than is reasonable contracting for epic.

  • @zekiozdemir420
    @zekiozdemir420 3 роки тому

    thank you.