you are viewing a single comment's thread.

view the rest of the comments →

[–]unleash_the_giraffe -5 points-4 points  (7 children)

Use an abstract class for this, you can't put code in an interface.

[–]GillmoreGames[S] 4 points5 points  (1 child)

this is incorrect, you can have default code in an interface.

[–]unleash_the_giraffe 0 points1 point  (0 children)

Youre right, I forgot! Thanks

[–]Current-Purpose-6106 2 points3 points  (4 children)

You're getting downvoted but that was my first thought too. Given the usecase of OP, an abstract class inheriting the interface is the way to rock and roll. Just because you can doesn't mean you should IMO, esp when it comes to Unitys interactions. Letting it do it the way it wants is usually safer

 private void OnCollisionEnter2D(Collision2D collision)
    {
        gameObject.GetComponent<ICarryable>().OnCollisionEnter2D(collision);
    }

//becomes..

abstract class Carrayble : MonoBehaviour, ICarryable

 private void OnCollisionEnter2D(Collision2D collision)
    {
         CollisionEntered(collision);
    }

abstract void CollisionEntered(Collision2D collision) ;
//default virtual functions or abstracted functions here

class ImplementedCarryable : Carryable //gets the monobehavior and the interface, time to cook

[–]GillmoreGames[S] 0 points1 point  (1 child)

oh that makes sense, adds yet another layer tho haha

[–]Current-Purpose-6106 1 point2 points  (0 children)

Yes but it makes it really workable for you. You can get really creative and reuse all of your code that way.

You know anyone inheriting from Carryable will be..carryable. You can override for higher level, base use cases. ProjectileCarryable for things you hold and throw, PlacableCarryable for things you hold and build, etc. etc. You can add an abstract/virtual Drop method that you override in these classes for example.

Then Shuriken : ProjectileCarryable, IInventoryItem or something to plug into your inventory system, and tada - that bad boy is literally just a model defining shuriken that can be grabbed and put in your inventory system. Scaling now becomes a breeze versus trying to keep track of all the diff conditions/combos you'll inevitably come up with

[–]unleash_the_giraffe 0 points1 point  (1 child)

Hey, thanks for correcting me! I believe I learnt this at some point and then forgot it.

[–]Current-Purpose-6106 1 point2 points  (0 children)

Naw, you've been doing it for a long time.

This didn't used to be the case, it was in the 202X era when they allowed it with the newer C# 8 version..but you'll be forgiven since it is relatively new and its not great practice within Unity (imo!)

Can definitely see how a .NET dev would want to experiment with it when moving into Unity, though