Hi
I was tempted to post this in Answers, but really what i’m asking for here is kind of based on peoples programming practice opinions, so I think this is better suited.
I’ve been using Unity for a while, but never really embraced the Component system, so now i’m trying to drop my reliance on OOP and really get into it, but I cant seem to get past this very small hurdle. I was hoping someone could help talk me through this simple example:
A Jumping Character.
If I was doing this the way I would usually do it: When the jump key is pressed, I check if the character is touching the ground, possibly via a short raycast, then I’d set the vertical velocity of the rigidbody to some jump strength value, and let gravity do the rest. All in one class.
I’d like to figure out how to break this down into separate components, so I started with creating a Jump component, which just handles increasing the velocity based on a Vector3 direction parameter and a strength parameter. Easy peasy.
class Jumper : Monobehaviour {
// ... parameters...
public void jump(){
// ... Make character jump...
}
}
and something similar for the ground check
class Grounded : Monobehaviour {
// ... parameters...
public bool check(){
// ... ray cast etc...
}
}
But now i’m stuck trying to work out how to work in the ground check without tightly coupling it to the Jump component.
So far I have tried creating a third component which, when triggered, will check the ground using the ground check and jump if its grounded.
// ... Require jumper grounded...
class JumpIfGrounded : Monobehaviour {
Jumper j;
Grounded g;
public void jump(){
if(g.check())
j.jump();
}
}
But the problem with this solution is that i’ll need to create a class like this for every combination of check and action. For example, what If i want to enable the character to perform a special dash, only when its touching the ground. I want to be able to use this same ground check for that too. At the same time, I don’t want the Jump or the Dash to always require a ground check, since I might want some creatures to be able to dash in the air, or double jump. Also, what if I create a Sticky platform? In that case it shouldn’t matter if the character is grounded. But ideally don’t want Sticky to have to know about Grounded, or Jump (although I really can’t imagine how that’s possible).
I have been tempted to use inheritance to solve this problem, but this is a red flag, because i’m trying to ditch OOP in favor of this Component based design.
How would you tackle this problem in a component based fashion?
p.s. I realize the level of component interchangeability I am searching for might not be possible, but perhaps in that case I can get close?