Search Unity

Set all velocity changes with a static function

Discussion in 'Scripting' started by Darkkingdom, Mar 31, 2019.

  1. Darkkingdom

    Darkkingdom

    Joined:
    Sep 2, 2014
    Posts:
    81
    Hey guys,

    sometimes I'm having an physic object which velocity doesn't behave as it should.
    Until now I always looked though dozen of scripts, until I found the line in which I do something stupid with rb2D.velocity = Vector2.zero, for example.

    Now to cut the debugging time, I build a static function in my helper class so I can easliy change each velocity for every object in one place.
    The code looks just like this:

    Code (CSharp):
    1. public static class Helper
    2. {
    3.     public static void SetVelo(Rigidbody2D rb2D, Vector2 velo)
    4.     {
    5.         rb2D.velocity = velo;
    6.     }
    7. }
    So my question is:
    Since all my objects set there velocity only with this function can this be troublesome for the performance or something like that?
     
  2. dgoyette

    dgoyette

    Joined:
    Jul 1, 2016
    Posts:
    4,195
    This approach shouldn't have any impact on performance, but I also don't think it gains you anything. Visual Studio already has tooling to find code reference properties/fields/methods, without needing to resort to something like this.

    For example, if you just right-click on the "velocity" field of a rigidbody anywhere in your code and choose "Find References" it will show you all the places in your code that you're setting/reading velocity. Note, this doesn't currently only show you cases where you Set velocity versus Get velocity, but I read that VS2019 will allow you to differentiate between the two.

    Anyway, my suggestion is just to use Find References this for unless you're going to add more functionality to your SetVelo call.
     
    Darkkingdom likes this.
  3. hippocoder

    hippocoder

    Digital Ape

    Joined:
    Apr 11, 2010
    Posts:
    29,723
    This is bad coding, adding abstraction just is terrible code because you aren't achieving anything with it that a good IDE can't fix.

    The performance overhead is minor but the codebase suffers from having a layer of pointless grease. Now if it was a function to make all things within a radius to add force, say an explosion and you called this function per object to work that out, this is normal and good code.

    But to make a function that does what a function already does (an abstraction wrapper) is bad. So make sure you aren't just showing us a simple version of what you actually plan.

    Also bad is using Velo. This is just raw laziness, and you should get into the habit of using longer variable names. SetVelocity is better and the IDE, a good one, will type this for you... especially if you use namespaces.
     
    Darkkingdom likes this.