- Home /
Simple abstractions. Reusing code outside of class
Hi,
Lets say i have this code:
SpriteRenderer sr;
Sprite sprite1;
Sprite sprite2;
void Awake()
{
sr = GetComponent<SpriteRenderer>();
}
void OnTriggerEnter2D(Collider2D other)
{
sr.sprite = sprite1;
}
void OnTriggerExit2D (Collider2D other)
{
sr.sprite = sprite2;
}
This is a simple example but imagine i do something like this
void SwitchSprite (Sprite newSprite)
{
sr.sprite = newSprite;
}
Then in this file I can do
SwitchSprite(sprite1);
etc.
What if i wanted to use this in my whole project?
should i create a public static void SwitchSprite (SpriteRenderer sr, Sprite newSprite);
// ?
is this worth doing in your experience?
Is creating simple abstractions like this a good idea?
thanks
It boils down to: do you save time using
SwitchSprite( sr, sprite1 ) ;
ins$$anonymous$$d of
sr.sprite = sprite1 ;
?
Or is there another reason to create such a method?
Answer by Baste · Jan 07, 2015 at 05:45 PM
For simple little things like changing the value of a variable, no, probably not.
For bigger things you keep doing a lot, but that doesn't belong together in a separate script or something that doesn't fit withing polymorphism, then yes, you can do this. It's usually referred to as "helper methods".
As a simple example: say you have an enum in your game named "Direction" that you use to specify movement to the north, east, south and west in some grid. Then it would be natural to define a static method MoveInDirection, that moves a vector in the given direction:
public static Vector3 MoveInDirection(Vector3 position, Direction direction, float length) {
if(direction == Direction.North) {
return position + new Vector3(1, 0, 0) * length;
}
....
}
A great way to do this in C# is through extension methods, which would allow you to do the same, but as a method on the class instead of a static method. If you made the above example as an extension method, you could do this:
Vector3 myVectorMovedNorth = myVector.MoveInDirection(Direction.North, 5f);
, which is nice. I do this a lot for things like rotating vectors around pivots, rounding Quaternions, and things like that.
As a rule of thumb, if you do the same thing several places in your code, put that thing in it's own method if it's more than one line of code. Be sure to give the methods good names - you shouldn't have to read through a method to understand what it does, the method name should be enough.
Your answer
Follow this Question
Related Questions
Do you tend to have scripts to mark prefabs 1 Answer
creating Custom class 1 Answer
Access the GameObject a class is attached to 1 Answer
Alternative to using prefabs w/scripts to save sets of data for use at runtime? 1 Answer
Spawning GameObjects with help of classes --- Attaching classes to GameObjects 1 Answer