Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

C# design patterns? reflection? wtf is this stuff?

Discussion in 'General Discussion' started by CaoMengde777, Sep 11, 2015.

  1. CaoMengde777

    CaoMengde777

    Joined:
    Nov 5, 2013
    Posts:
    813
    okay... so i guess hot shot programmers and stuff throw lingo around i have no idea how to learn these things..

    reflection? .. idk what that means exactly..
    design patterns?
    singleton?

    stuff like this... whats this stuff? LOL
    I guess its methodologies? .. doesnt really have anything to do with .. required to actually work with???

    so.. ive learned some C# .. variables, data types, collections, methods, events delegates, working with GC, structs/propertys, classes, encapsulation, inheritance, interfaces, LINQ, exception handling, lamba,

    alot of material i can find talks about these things..
    what about "hot shot programmer lingos" LOL

    guess its entirely unnecessary for a single guy to know? its just team/ working for someone crap? LOL
    (dont really want to work programming seems boring as F .. i mean, working on some1 elses crap? ew..)

    my background is modding and tinkering, read some ebooks, youtube tutorials, edx.org class on C#,
    split my time learning C#, unity, blender, substance, lmms, guess im not proficient in any one area, have enough knowledge that i could be making a pretty sweet 3d game now, but want to become proficient in all.
    ... made a ton of simple projects to learn basics of things...

    i see this site has a $80 book or whatever it is about design patterns http://www.dofactory.com/net/abstract-factory-design-pattern ... but if its something only really needed for a job, i dont care about it LOL (altho yea)

    okay.. like here: https://msdn.microsoft.com/en-us/library/ee207183.aspx
    "Reflection" is among the list to the left side...
    is this list 'complete' .. like is that ALL the.. "reflection lingo type things" to know?

    lol... guess looking for general advice or something? :)
     
    Last edited: Sep 11, 2015
  2. CaoMengde777

    CaoMengde777

    Joined:
    Nov 5, 2013
    Posts:
    813
    I guess its Software Engineer type stuff? ... lol
    lol idk when you go to learn C# .. they never talk about these things... or .. i suppose the majority of material is about the basics... well, i want to know the next level..

    okay a book on amazon "C# in depth" .. doesnt say anything about these things ^ (judging by table of contents)

    various code people share, they use these lingos.
     
  3. jgnmoose

    jgnmoose

    Joined:
    Apr 1, 2014
    Posts:
    44
    These are more advanced design concepts. Keep in mind that the C# we use in Unity is not *technically* a complete application. Design patterns kind of make more sense when you coding the entire application as various classes. We are basically using these classes to extend objects most of the time.

    Singletons are something you'll see done in Unity. The basic idea is that you only want this class to instantiate once. An example might be a GameState or MusicManager class (or both). For example, these things stay loaded and do not get reinitialized between levels.

    Encapsulation, and Single Purpose Design are some other popular patterns that you'll see in game programming. Encapsulation refers to "hiding" the properties/variables of a class from the other classes. A very simple version of this is basically you should never manipulate variables in one class from another. Instead you provide a function for other classes to call that manipulates the data with whatever arguments you might want to pass in. Single Design Principle is the idea that each class should do one thing. For example, a ParallaxCamera class really shouldn't be handling game state or player score.

    To be honest, a lot of this stuff is something you'll probably do on your own through trial and error. It matters a lot more on a team where there has to be a standard. You get enough people with their own ideas on how to code on a project and it can hacky and ugly quick.
     
  4. CaoMengde777

    CaoMengde777

    Joined:
    Nov 5, 2013
    Posts:
    813
    thanks!
    yeah i was thinking too maybe i could extend my learning to Visual Studio, and universal apps for Windows or something,

    but yeah thanks for helping clarify, so it is team.. standardization concepts, for the most part.
    heheh i was all sorts of confused when i wrote the OP ..

    yeah i figured/ have read alot of it is stuff you end up using alot just naturally.. but i suppose ill have to go and learn the lingos
     
  5. XGundam05

    XGundam05

    Joined:
    Mar 29, 2012
    Posts:
    473
    The jargon is good to learn for design patterns...if only because if makes it easier to talk about things. E.g. instead of "making a non-static class with inheritance an essentially static class" you say "singleton".

    Reflection is mostly a .Net/Mono thing. A very useful thing though. It lets you get details about classes, variables and method signatures at runtime. Things like "this method is named X, and was decorated with these attributes, which were populated with these other values". It's also kind of a pain to get started with. I'm also not very good at explaining it without code (and typing code on my phone is...unpleasant).
     
    landon912 likes this.
  6. Tomnnn

    Tomnnn

    Joined:
    May 23, 2013
    Posts:
    4,148
    Singletons probably get used more in games than anything else, I can understand them being hard to learn because an out of context search for them will give you plenty of negative feedback for them haha. Ok, singletons...

    You know how static variables work, yes? If a variable is static, it's available to anything via Classname.StaticVariable. A singleton is a static variable of the class.

    public static Game singleton = this;

    That is usually how mine are setup. A singleton of my game manager. Then any script anywhere can access the public variables of Game, via Game.singleton.publicVariable. Want to find enemies without using GameObject.Find? Declare a public list of enemies in Game. Then on your enemy start function, you can do Game.singleton.enemies.add(self); and when your player needs to access them your player can call Game.singleton.enemies and iterate through the collection.

    Reflection I don't really use myself since there as less performance heavy workarounds to achieve the same effect. Of course there are cases where something can only be achieved with reflection, like dynamically loading assemblies. I don't know what reflection is and I don't know what "dynamically loading assemblies" means but I know those words together are accurate. If you're really curious about it look into dynamically loading assemblies with reflection :p

    Design patterns really goes out the window with games. Or rather, there are more options. Brief example : a singleton is a common practice. Even UNET has a singleton (even called singleton) for its network manager.

    check it out in the docs, NetworkManager.singleton :D
     
  7. GarBenjamin

    GarBenjamin

    Joined:
    Dec 26, 2013
    Posts:
    7,441
    Use only the stuff you need to keep your code as simple as possible, clean but simple, despite software engineering aficionados sometimes rolling their eyes at such things. There is value in the stuff for certain but it is also easy to get so caught up in it you end up over-engineering everything. That makes everything more convoluted more difficult to update. The patterns are to make software applications easier to maintain, remove spaghetti code structure and so forth not to complicate things just for the heck of it.
     
    ZJP likes this.
  8. frosted

    frosted

    Joined:
    Jan 17, 2014
    Posts:
    4,044
    Reflection is a powerful and useful set of tools for manipulating code from code. I have a set of attributes that I use to avoid having to manually wire stuff up in editor.

    [FromParent]
    protected UIPanel Panel;

    [FromGameObject]
    protected UILabel Label;

    All these really translate to are GetComponent calls, but marking it on the field like this is really clear. Reflection let's me write code that scans the class for these tags, get the fields or properties they're connected to and populate them.

    I don't really use these tags anymore, and I'm not even sure I think they're good practice at this point. But they were damn convenient and very clear.

    Reflection can do a crap ton of stuff that isn't normally possible.

    But it's also not really something you generally want to do in game dev, unless you're building out some tools that are on the more ambitious side.
     
    landon912 likes this.
  9. AndrewGrayGames

    AndrewGrayGames

    Joined:
    Nov 19, 2009
    Posts:
    3,822
    The reason for this is, reflection is slow. Pretty much, reflection means that your assembly is reading from itself to get information that it couldn't normally get in 'normal' runtime.

    Design patterns are good things to know; they're recipes that solve common problems. They're not always useful, though.

    Singletons are a design pattern that are reviled by some because they introduce global state - as a result, this is considered an anti-pattern to object-oriented programming, where things are objectified to avoid global state. Global state is considered bad because it complicates maintenance. If you need a set of functions that exist "out there", you might consider writing a static class.

    Now, Singletons are still good to know for other reasons. I have a Unity Code Pattern™ of my own that I call "Manager Object." Pretty much it's a game object that persists across scenes, and has code to self-destruct if an object of the same type already exists. It's global to the game, but doesn't break the code's compartmentalization. This is because, the way Unity works, even if you create a static class when scenes change the state gets dumped...including that static class that exists "out there." Only an object with "DontDestroyOnLoad" A) continues existing, and B) keeps its state, which is what I want.

    You can see this in action in my PersistentSingularObject behavior.
     
    Last edited: Sep 11, 2015
  10. XGundam05

    XGundam05

    Joined:
    Mar 29, 2012
    Posts:
    473
    @Asvarduil I have had my fair share of concurrency issues from singletons (yaay for classes that are great-grandchildren of a singleton base...so you have no idea that you have a static class >.<). But an instance that they are useful in, like you say, is that you can inherit from them (you can't with static classes). Granted, this can lead to the aforementioned skull/wall destroying issues.
     
    AndrewGrayGames likes this.
  11. Tomnnn

    Tomnnn

    Joined:
    May 23, 2013
    Posts:
    4,148
    The potential downside being that this all happens at runtime, right? So if done wrong there could be performance hangs?
     
    AndrewGrayGames likes this.
  12. RockoDyne

    RockoDyne

    Joined:
    Apr 10, 2014
    Posts:
    2,234
    Considering Unity is built on reflection magic, you've probably experienced these issues before.
     
    Tomnnn likes this.
  13. AndrewGrayGames

    AndrewGrayGames

    Joined:
    Nov 19, 2009
    Posts:
    3,822
    That's true. I've found few times where one would want to inherit from a Singleton, but it is possible, so I find it entirely believable, and inevitable that someone has, or will. Further, it was or will be the best possible solution for some problem, downsides notwithstanding.

    I like my component implementation more, because it's at least understandable. You know that the component is set up to persist across scenes. It also doesn't interact with anything else directly; it merely composes the game object, with the other things that the Persistent Object needs to do its job.
     
    XGundam05 likes this.
  14. ZJP

    ZJP

    Joined:
    Jan 22, 2010
    Posts:
    2,649
    This..
     
    AndrewGrayGames likes this.
  15. goat

    goat

    Joined:
    Aug 24, 2009
    Posts:
    5,182
    It's the same concepts that programmers have used before but repackaged. So essentially it's new lingo designed to make older developers feel inadequate. A bit like slang. Just buy a book on C#.
     
  16. AndrewGrayGames

    AndrewGrayGames

    Joined:
    Nov 19, 2009
    Posts:
    3,822
    Fo rizz', G-drizz. Now shake a leg and go ham on that biscuit.
     
    ElectroMantis and Deleted User like this.
  17. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    Yep, and when you use unity you are using a pattern without even knowing it. It's called, surprisingly enough, composition or component design. Most people don't realize it because they are dragging and dropping components.
     
  18. AndrewGrayGames

    AndrewGrayGames

    Joined:
    Nov 19, 2009
    Posts:
    3,822
    And this answer is what makes the OP's questions worth it. Design patterns are something of a rabbit hole that, once explored, leads deeper, but also leads to useful insights. Components are a great one to know.

    In fact...

    There's a great book that you can read for free, called Game Programming Patterns. I bought a hardcopy from Barnes and Noble, but it was worth it - while the author of this work talks about certain 'Gang of Four' patterns including components, he goes into some patterns that are specific to Games work. The OP should read that, it will be of great use.
     
    Dustin-Horne, landon912 and Socrates like this.
  19. XGundam05

    XGundam05

    Joined:
    Mar 29, 2012
    Posts:
    473
    Most assuredly. If I could refactor the codebase at work to use composition in the places it makes sense, I'd do it in less than a heartbeat.

    I'd also refactor out a lot of the singleton use...I'm guessing it was a case of some architect before my time that had just discovered the singleton pattern and went "yaaay! Erything must be singelton!!1!!" -.-
     
    AndrewGrayGames likes this.
  20. goat

    goat

    Joined:
    Aug 24, 2009
    Posts:
    5,182
    See what I mean? Inadequate linguistics.
     
  21. AndrewGrayGames

    AndrewGrayGames

    Joined:
    Nov 19, 2009
    Posts:
    3,822
    (Rap Beat)
    I know you can read that; it's there, and it's true.
    Believe in the me, who believes in you.

    (That was an example of recursion, btw.)
     
    Dustin-Horne likes this.
  22. goat

    goat

    Joined:
    Aug 24, 2009
    Posts:
    5,182
    Rose are red and the violets are blue and if that's now enough so are you.
     
  23. theANMATOR2b

    theANMATOR2b

    Joined:
    Jul 12, 2014
    Posts:
    7,790
    All this is very interesting, though I understand very little of it. Maybe my brain is learning thing I just don't consciously know about. :)
    Sorry this is only vaguely related, @Asvarduil - the trademark symbol here - is that trademarked?
    Just doesn't seem like a trademark-able thing to me, admittedly I know the least about TM compared to other classified content. A quick answer is completely fine - to keep the thread on target.
     
  24. AndrewGrayGames

    AndrewGrayGames

    Joined:
    Nov 19, 2009
    Posts:
    3,822
    It's me being silly. It's not actually trademarked.
     
    theANMATOR2b likes this.
  25. Tomnnn

    Tomnnn

    Joined:
    May 23, 2013
    Posts:
    4,148
    Is that so? Damn, I had no idea! Whelp, looks like I'm in the market for a new engine. An engine known for being one of the best performing mobile engines with low requirements is built on reflection? That mixture is more unstable than I am!

    That sounds like a great line for a horror game / movie like nightmare on elm street. An evil force that requests that you believe in it, and the more you believe in it the more powerful it becomes. We shall call this game... the placebo effect!
     
    AndrewGrayGames likes this.
  26. Meltdown

    Meltdown

    Joined:
    Oct 13, 2010
    Posts:
    5,796
    Check out gameprogrammingpatterns.com, really useful stuff, its in C++ but the ideas and concepts are still the same!

    Once you practice the various patterns, and use them in small real-world or prototype examples, it quickly becomes clear which patterns to use and when. Generally I've found a mix of patterns work for me in the Unity projects I work on.

    I really try to avoid singleton's though. I usually only use them for Utility library stuff like a SoundManager or other helper stuff I need to easily access in my game.

    I find an event/subscriber solution using AdvancedCSharpMessenger works well for most other cases and avoids hard-coded dependencies and creates cleaner seperation of logic.

    When it comes to state machines the state design pattern is the clear winner here,

    Also read up on the SOLID principle, those are good rules to live by and will make your life easier when it comes to working on larger codebases, but you should by all means use them even in small codebases.

    It's really hard to explain what pattern to use and when trying to explain it to another developer, the best thing is to get your hands dirty and practice, and over time you'll know what works best for you.
     
    Last edited: Sep 12, 2015
  27. AndrewGrayGames

    AndrewGrayGames

    Joined:
    Nov 19, 2009
    Posts:
    3,822
    You know, that's actually not a terrible idea. The final twist? As you've began believing in the Placebo...it's been possessing you murdering dudes. The game ends with you no longer being you. Better still? Automatic sequel hook.
     
    hippocoder and Tomnnn like this.
  28. RockoDyne

    RockoDyne

    Joined:
    Apr 10, 2014
    Posts:
    2,234
    Last I heard it's how all the monobehaviour functions get called/wired up, and why strings were so common before UT started embracing generics. It's supposed to be the big reason why instantiation is such a performance hit, which is where most of it comes in.
     
    Tomnnn likes this.
  29. Tomnnn

    Tomnnn

    Joined:
    May 23, 2013
    Posts:
    4,148
    Psychological horror leading up to a decent story twist. It'd be like the all those films that make you see terrible things until you react in a way that causes harm to innocent bystanders.

    Oh, thanks for that info. Object pooling is more important than I knew!
     
  30. AndrewGrayGames

    AndrewGrayGames

    Joined:
    Nov 19, 2009
    Posts:
    3,822
    Ooo that's a better idea! It mutates you into a clone of Donald Trump! Muahahahaa!!!
    Ba-da-TISSH!
     
  31. Tomnnn

    Tomnnn

    Joined:
    May 23, 2013
    Posts:
    4,148
    Oh, thanks for that info. I see object pooling is even more important than I thought.
     
  32. darkhog

    darkhog

    Joined:
    Dec 4, 2012
    Posts:
    2,218
    Regarding singletons, in my games I usually have something like this:

    Code (csharp):
    1. public static class Globals {
    2. public static int score = 0;
    3. //...
    4. }
    for things that I want to persist between levels or just I want make sharing data between multiple monobehaviours easier. No need to play around with loadaddittive (as one guy did it in tutorial on how to share things between levels, probably live training but not sure) when this is easier and faster way to do so.
     
  33. sluice

    sluice

    Joined:
    Jan 31, 2014
    Posts:
    416
    As other mentioned here: A Singleton is simply a Design Patterns.
    Design Patterns are simply a proven reusable solution to a commonly occurring problem.

    If you ever dream to work at one of the big companies (in gaming or not) as a software engineer, it's imperative that you know a few design patterns and are able to explain them... ;)

    In my opinion, the best Design Pattern introduction book: Head First Design Patterns
    It really helps to better understand the Gang Of Four book holy bible of Design Patterns.

    Ever heard of MVC? Ever wondered what it is and how it really functions?
    Answer: Essentially it's just 3 design patterns (Composite, Observer and Strategy pattern) put together to better implement user interface...

    But before diving into Design Patterns, you have to understand Object Oriented Programming...
    This series would be a great start, in my opinion: Foundations of Object Oriented Design
     
    Last edited: Sep 22, 2015
  34. Naphier

    Naphier

    Joined:
    Aug 4, 2014
    Posts:
    114
    If anyone's interested, I'm on a quest to bring together design pattern examples in Unity so that people can see concrete examples of them in our favorite development environment ;)
    I have 3 cases up: Command, Abstract Factory, and Flyweight (I'm not happy with flyweight).
    I'm probably going to leave out singleton for a while since there are tons of singleton examples floating around out there, but will eventually put up a Monobehaviour singleton and a non-derived singleton.
    I'm now looking for contributors as I can't do it all on my own and I'd love it if we could have multiple examples of each pattern.
    If you're interested then check out the repo at https://github.com/Naphier/unity-design-patterns
    And shoot me an email via GitHub and I'll provide you access if you'd like to contribute.
    Cheers!
     
    Rodolfo-Rubens and Martin_H like this.
  35. ChrisSch

    ChrisSch

    Joined:
    Feb 15, 2013
    Posts:
    763
    I started programming for the first time in Unity, so just as OP a lot of "basics" and terms are unfamiliar to me. I'm familiar with OOP, but besides BASIC i never programmed outside Unity (seriously at least). So a lot of times I had issues that were common sense or simple to others but not me. For instance, I can do a lot in Unity, but I have no idea how I'd start making a console app from scratch. My timetamble is always hectic, but I downloaded SharpDevelop to learn programming in C# "from scratch" when i have time. :D
     
  36. tiggus

    tiggus

    Joined:
    Sep 2, 2010
    Posts:
    1,240
    You might consider Pub-Sub and Observer, I use those quite frequently in Unity.
     
  37. landon912

    landon912

    Joined:
    Nov 8, 2011
    Posts:
    1,579
    @Tomnnn If you use Singletons, you probably want an order independent solution. In the Awake method of other MonoBehaviors, there is a chance that your singleton isn't prepared.

    Here is a better solution:

    Code (CSharp):
    1. private static MySpecialClass mInstance;
    2.  
    3. public static MySpecialClass Instance
    4. {
    5. get{ if(mInstance == null){ mInstance = FindObjectOfType<MySpecialClass>();} return mInstance;}
    6. }
     
  38. darkhog

    darkhog

    Joined:
    Dec 4, 2012
    Posts:
    2,218
    Yeah, but IMO my solution is the easiest. Aside of making static class with static members, no engineering is needed.
     
  39. landon912

    landon912

    Joined:
    Nov 8, 2011
    Posts:
    1,579
    Easiest and the worst. Not to be rude, but that's a very poor use of OOP. But hey, it's in Unity, where it's incredibly hard to write good code because of all their own bad practices that are forced upon you. (I'm looking at you, Input class)
     
    Last edited: Dec 6, 2015
    Ryiah likes this.