Search Unity

Trying to develop but cant design my code!

Discussion in 'General Discussion' started by yian-dev, Jul 12, 2017.

  1. yian-dev

    yian-dev

    Joined:
    Jun 26, 2017
    Posts:
    20
    Hello dev's,
    I keep facing this major wall i cant get around which is code design, and making scripts code and assets modular/drop-in without errors.
    I know how to use unity and how to code, but i always get stuck in code design when my game prototypes grow bigger.
    Im currently making a new game prototype third person, i made the character have some basic skills, UI and started to work on the enemy but once again i find everything too randomly coded with scripts bolten on all over the place.

    Do you guys have this problem and how do you aproach code design solutions? this is currently my number one issue with game dev'ing/software dev no matter the language or engine i cant design proper code when things become big and i get stuck.

    How do i design my scene to instantiate my complex player with many scripts/behaviour without error, load his data from a savegame, instantiate UIskills slots, health bars, setup the world properly etc?
    I currently have no solution to code design i end up spending hours rewriting everything again and again not getting anywhere, i try to write down in pseudo code what is doing what but it doesnt help when some variable or function doesnt work as i want it to(api or C# limitations) and the whole thing was a waste of time.
    Design patters are complicated and i end up with more errors than fixes, i keep trying watching others code on youtube but not much improvement.

    Are there any books about C# code design or unity game arhitecture, aimed at beginner/intermediate dev's? i can do stuff in unity i can make stuff work, implement features but when it comes to design im 0, i cant complete any game like this.
     
    neoshaman likes this.
  2. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    21,203
    Many of the best code design books are language agnostic. Choice of language for a code design book is often the language the author best understands so before you pass up on a book solely because it used a different language consider you may be passing up something that would have actually applied to you.

    Here are a couple examples.

    https://www.amazon.com/Code-Complete-Practical-Handbook-Construction/dp/0735619670
    https://www.amazon.com/Pragmatic-Programmer-Journeyman-Master/dp/020161622X

    Here is the list they're part of.

    https://stackoverflow.com/a/1713
     
    alexanderameye and elmar1028 like this.
  3. mysticfall

    mysticfall

    Joined:
    Aug 9, 2016
    Posts:
    649
    Aside from learning common software design principles, I'd also recommend to study source code of well designed assets and try to take hints from them.

    It seems that Unity has many of its own quirks, like its ubiquitous use of such heavy weight component as MonoBehaviour, or its complicated lifecycle callbacks (implemented by some 'magic' methods), limitation with serialization, communication with 'messages' (SendMessage/Invoke), and so on.

    As such, even though knowledge of common software design principles can certainly help, it sometimes clashes with such peculiar aspect of Unity platform, so it might be necessary to spend some time to learn what common practices more experienced Unity developers tend to follow when they are building complex assets or games.
     
  4. Player7

    Player7

    Joined:
    Oct 21, 2015
    Posts:
    1,533
    ...if you really want to see what others would do you have to share code and how you're doing something. I don't think anyone is really going to be able to offer much help to other than suggesting things you're already know to do or check.

    Handling growing projects with more and more features is an art that just takes time learning and doing and learning from doing. Hell I'm still learning, just that I've reached the point where I can't be bothered to go back and redo things again. So just making it work and going through bugs and making S*** work regardless of how I might do it again another time. Code refactoring as you go can help aswel as putting in debug code that can be toggled for different parts of your game to see what's going on. Unity has S*** built in debug tooling, so start finding assets that can somewhat assist in those areas... dev consoles, better debug scripts etc.. help keep an eye on more things going on in your game while in game and make it easier to debug things quicker when something unexpected is happening.
     
  5. QuackProductionz

    QuackProductionz

    Joined:
    Jun 12, 2017
    Posts:
    15
    The way i design my code is simple every function and variable pretty much explains itself even after a month i can come back to it and see what name of my function is example ChangeDirectionOfMovementOnClick(); i know ya should not really do that but im Dyslexic and coding is hard enough lol also comment everything, code design is like an art beautiful code that is almost like English .Other tip i use never exceed 500 lines of code if you are say doing a character Movement have a script just for movement ,shooting ,death probably will be inside movement then just connect em using instances
     
    theANMATOR2b likes this.
  6. QuackProductionz

    QuackProductionz

    Joined:
    Jun 12, 2017
    Posts:
    15
    Also if connecting scripts is not your thing make custom functions Movement(),Shooting(),Death(); then just call them from update
     
    theANMATOR2b likes this.
  7. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    21,203
    On the contrary, while your example may be a little verbose, you are supposed to name the variables and functions in a way that indicates their job. Code design though isn't choosing proper names. Code design is about choosing the way you implement your algorithm (eg choosing between a singleton and a static class).

    By the way I recommend learning proper use of comments in code and learn about C#'s document comments.

    https://msdn.microsoft.com/en-us/library/b2s063f7(v=vs.100).aspx

    If you're using Mono Develop or Visual Studio you may have noticed a tooltip like the following image. Those tooltips are made with document comments. You can do the exact same thing with your own code.

    tooltip.png

    The Mathf.Clamp document comment looks something like this under the hood.

    Code (csharp):
    1. /// <summary>
    2. /// Clamps a value between a minimum float and maximum float value.
    3. /// <param name="value">The value you want to clamp.</param>
    4. /// <param name="min">The minimum range of the value.</param>
    5. /// <param name="max">The maximum range of the value.</param>
    6. /// <returns>A value clamped between min and max.</returns>
    7. /// </summary>
    8. float Clamp(float value, float min, float max)
    9. {
    10. ...
    11. }
    Same concept can be applied to variables too but most people just place a one line comment on the side if the variable isn't obvious or if additional information is needed.

    Code (csharp):
    1. public float weight;  // in kilograms
     
  8. snacktime

    snacktime

    Joined:
    Apr 15, 2013
    Posts:
    3,356
    A lot of how I learned follows a couple simple rules. One, I assume the problem is already solved. So I look for the best solution and if it's something I'm new at, I look at how they designed it.

    Even after 20+ years at this, I NEVER design something I'm not familar with without looking at how people who are experts solved it. And I usually copy their design for the most part.
     
  9. QuackProductionz

    QuackProductionz

    Joined:
    Jun 12, 2017
    Posts:
    15
    whoa nice didnt even know about that yeah im still learning as i go ive developed some habits im lookin into that i mostly use mono but last two-three weeks have been looking at Visual Studio and so far its sped things up quite abit
     
  10. yian-dev

    yian-dev

    Joined:
    Jun 26, 2017
    Posts:
    20
    Thanks didnt expect so many answers.
    If one thing i should have been doing more is reading good written code, well if i coud find any. Most C# books i read or tried reading had the most simple examples. Reading code on github is way too much, so many clases and techniques im not even sure what im reading most of the times.
    I have no college education so im learning however i can.

    Generic design theory books, i find them not very helpful, they might form my mind better, any good reading does i think, but im more of a practical guy, if i can read simple good code implementation in C# or Unity C# api that could scale to most games and hundrets of scripts that would be ideal, ofcourse there is no silver bullet like that.

    I wish UnityTech would make some design tutorials from beginners to advanced, how do you structure your code in such a way that its scalable and easy to understand where to put functionality and expand without spaghetti code.

    Usually how i work best is learning all this stuff the practical way and by reading code then later down the road read more in depth theory to improve my code crafting, i cant do the opposite tough if you feed me hundrets of pages of theory without a ton of practice its all in vain.

    I might just suck at organizing my work and the code, i should improve the way i work since its messy.
    Unity being so easy to implement some quick behaviour and drop scripts on objects you forget that good games are made by good desginers(software/art/sound etc), designers should work on design while coders should focus on their specific implementations.
    So before anything i should go back and take a different aproach and actually design something before i write even 1 line of code.
     
  11. elmar1028

    elmar1028

    Joined:
    Nov 21, 2013
    Posts:
    2,359
  12. QuackProductionz

    QuackProductionz

    Joined:
    Jun 12, 2017
    Posts:
    15
    I wouldnt bother with education for learning games and coding from my experiance they always have you open the roll a ball tutorial when its game design class ...i could do that at home lol and when its programming its rarely doing game projects its more learning to code in full like as if you were going to be a programmer only not much game programming which in my opinion is worst way to learn code for games your best option for learn to code and getting better at writing neat easy to read code is Youtube ,Google,and forums .Get a pen and a notebook write down the type game you want to make and the games you actully can make then write down say for example main character player what is his most basic function "Movement" so write down what you think goes into that like effecting the transform so most likely vector 3 will come into it if 3D or if your using physics to move it say for a platformer Rigidbody stuff the way id handle this is update will be used for calling my custom functions such as movement
    you do the movement logic and "COMMENT THE DAMN CODE" then call it from Update this is just a small example but for me it has helped me go from 3D artist to game programmer and be able to make simple games il send a code snippet of a small game im working on now .
     
  13. QuackProductionz

    QuackProductionz

    Joined:
    Jun 12, 2017
    Posts:
    15
    public class BallController : MonoBehaviour
    {
    //VARIABLES COMMENTS

    private Rigidbody rb; //ref to the Rigidbody attached to the player/Ball
    [SerializeField] //allows modifyin in the inspector,we cant access from other scripts
    private float speed; //speed of Ball's movement
    private bool gameStarted; //true/false variable for check if game has started
    private bool gameOver;

    private void Awake() //first function that gets called
    {
    rb = GetComponent<Rigidbody>(); //cache a ref of the Rigidbody ,it is now referred to as rb
    }

    private void Start()
    {
    gameStarted = false; //on game start gameStarted is false,so ball does not move straight away
    gameOver = false;
    HasGameStarted(); //function to check if game has started ,ball begins moving forward
    }
    private void Update()
    {
    MakePlayerFallOffPlatforms(); //call the function that handles player falling off platforms
    ChangeDirectionOnTap(); //call the function that handles user input for player/Ball movement
    }

    void MakePlayerFallOffPlatforms() //function that handles checking if we on the platforms or not
    {
    Debug.DrawRay(transform.position, Vector3.down, Color.red); //draw a ray cast visually down from player to ground
    if (!Physics.Raycast(transform.position, Vector3.down, 1f)) //check if the ray is touching platform or not
    {
    gameOver = true; //the game is over /we fall and die
    rb.velocity = new Vector3(0, -25f, 0); //make player fall when no longer on platform
    TurnOffCameraFollowPlayer(); //calls the custom function for disableing cam follow
    }
    }

    void TurnOffCameraFollowPlayer()
    {
    Camera.main.GetComponent<CameraFollowPlayer>().gameOver = true;
    }

    void ChangeDirectionOnTap() //change the direction of the Ball when player taps screen
    {
    if (Input.GetMouseButtonDown(0)&& !gameOver) //if tap or LMB is pressed
    {
    if (rb.velocity.z > 0) //and if ball is moving along z axis
    {
    rb.velocity = Vector3.left * speed; //change direction to moving left
    }
    else //or if moving left along x axis
    {
    rb.velocity = Vector3.forward * speed; //change direction to move forward
    }
    }
    }
    void HasGameStarted() //function that checks if the game has started ,if so ball begins moving forward on tap/click
    {
    if (gameStarted == false) //if game has not started
    {
    rb.velocity = Vector3.zero; //no movement for the Ball
    }
    else //if it has started
    {
    if (Input.GetMouseButtonDown(0)) //and we tap/click
    {
    CheckGameStatus(); //call the function that checks if the game has started
    }

    }
    }

    void CheckGameStatus() //function that makes ball move forward if game has started ,checks the status
    {
    if (gameStarted == true) //if game has started
    {
    rb.velocity = Vector3.forward * speed; //Ball begins moving forward on Tap/Click
    }
    }

    private void OnTriggerEnter(Collider other)
    {
    if (other.gameObject.tag == "Diamond")
    {
    Destroy(other.gameObject);
    }
    }

    }
     
  14. QuackProductionz

    QuackProductionz

    Joined:
    Jun 12, 2017
    Posts:
    15
    I know i S***ted on the Roll a Ball tut but that is a great one to practice tidy code on dont put your comments above your code put it on same line more or less its really up to you starting off there is no right or wrong way as long as you get the job your trying to do done release the project then when problems appear fix them best way to learn is doing a book and a teacher will not do you much good when your on your own trying to make your own game make the mistakes learn from them you wont memorise code off by heart but the more ya do it you will find your own way of getting things done
     
  15. snacktime

    snacktime

    Joined:
    Apr 15, 2013
    Posts:
    3,356
    That is generally considered bad commenting.

    Comments for the method itself that intellisense can show is good.

    Comments on what code within the method is doing is what is bad. Those kinds of comments should really only exist if what you are doing is very non obvious and somehow important for someone else modifying your code to know. Like maybe why you used a specific algorithm.
     
    mysticfall and Kiwasi like this.
  16. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Dude, code tags.

    Most of those comments are a waste of time. Comments should never say the same thing the code does. If they do, you haven't written the code properly.

    Comments should say things the code doesn't say. Like why you choose to do something a certain way.

    Another bad practice.


    Actually there is. Best practices exist for a reason. Mainly because devs have tried to do otherwise and failed in the past. There is no point making every mistake on your own.
     
  17. daxiongmao

    daxiongmao

    Joined:
    Feb 2, 2016
    Posts:
    412
    I think you just need to look at more simple problems. Coding is really just solving lots of problems. Some start out big but you just keep break them into smaller ones. Patterns and practices give you ways to break those problems down.

    To me the number one requirement for a programmer is being able to break down and solve a problem in small workable steps.

    You need to get to the point where you understand those simple examples well enough you can use them to solve a larger problem. Because most programming at its simplest is just "if a == b then doC()"

    if you see well written code that is too complex it's because you don't understand the simpler principles yet.
    Just takes time and practice.

    Reading your comments though why do you stop and rewrite it? Is the code not working or you just don't think it's good code?

    If it's the latter just push on. It sounds like you don't have enough experience to decide if it's good or bad.
    So keep going. Then when you get to the point things are done and working you can go back seeing the big picture and start looking at your code and seeing things like this looks like i might be able to use inheritance here. Or visitor or strategy. Then you will start to see the benefits of these things in your own code and realize your thought process.
    Just seeing an example of a implemented pattern isn't going to help much.
     
    Ryiah and Kiwasi like this.