Search Unity

When to use a new class... when to just keep it all together

Discussion in 'Scripting' started by Vimalakirti, Aug 23, 2011.

  1. Vimalakirti

    Vimalakirti

    Joined:
    Oct 12, 2009
    Posts:
    755
    I have my player doing several things that each have their own animation, duration, limitations, such as:
    Reloading ( can move, can't shoot, takes time, restores ammo)
    Using MedKit (can't move, can't shoot, takes time, restores health)
    and some other things.

    So, My character controller script grows and grows. Each of these items needs a state. The movement input needs to be surrounded by if(!moving !reloading) of course, can't get away from that, but there are other things. The animation needs to be triggered, and a timer needs to be set, which requires another float in addition to the bool state, etc.

    So my question is: is it a better programming practice to create a new class for each of these things (Reload.cs and MedKit.cs) that I instantiate when they occur, letting the class keep track of the timer, trigger the animation, then tell the controller script that it's done and then destroy itself,... or should I just allow my controller script to grow and have more variables floating around?

    Or am I just thinking too much and it's all a matter of style?
     
  2. Jaimi

    Jaimi

    Joined:
    Jan 10, 2009
    Posts:
    6,208
    it's better to strip these out into new classes. Keeps things tidier, and makes it less likely you will have problems from unintended effects. Keep all the stuff related to the behavior ecapsulated in the particular class that implements the behavior.
     
  3. Vimalakirti

    Vimalakirti

    Joined:
    Oct 12, 2009
    Posts:
    755
    Thanks, Jaimi!
    It is tidier to have things encapsulated isn't it.