is there a way to write a method to call ‘addforce’ to either a rigidbody or a rigidbody2d parameter?

Generics won’t help because there is surprisingly no common parent class with AddForce. Rigidbody and Rigidbody2D both inherit from Component.

I see you as having two options:

Firstly, and most simply, only use Rigidbody and use constraints to keep it in 2D when needed.

In the case where this isn’t an option, a simple ‘if’ statement would do:

void applyScrollForce(Object rb) {
    var force = _scrollController.scrollDirection * _scrollController.scrollSpeed * Time.fixedDeltaTime;
    if(rb.GetType() == typeof(Rigidbody))
        ((Rigidbody)rb).AddForce(force);
    else if(rb.GetType() == typeof(Rigidbody2D))
        ((Rigidbody2D)rb).AddForce(force);
}

Naturally you probably want to cache the type instead of checking and casting every frame.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top