How would you implement the described scenario?
I am struggling with Code design in my 2D Game and having some troubles with the component based system of Unity.
My Design:
My main problem is Single Point of Truth. I want to implement basic movement (to left and to right) only once in Character which I could achieve by programming there something in Update(). However the way the Character is moved from Player and NPC is different of course. The Player is moved by Player Input and NPC is moved by configured Properties. As a example in Player I would need a Update() too in which I track Input and manipulate with this data the Character movement. This doesn't work because Unity only calls the Update of one class. Which I fully can understand.
So I am breaking my head how to design this scenario in a good way. I am very thankful for any recommendations or some good documentations/guides which I can read.
PS: I don't have any code to share. This is just a scenario which I am considering about.
Answer by Hellium · Jul 02, 2018 at 09:16 PM
I would manage the movement in a dedicated component (a.k.a class). Either use inheritance or interface implementation (better but not really handy in Unity)
Inheritance
Declare an abstract class called
MovementController
declaring a single functionMove( Character character )
In the
Character
class, declare apublic MovementController MovementController
In the
Character
's class, makeUpdate
aprotected virtual
function callingMovementController.Move( this )
Create two other classes :
PlayerMovementController : MovementController
andNPCMovementController : MovementController
implementing theMove
functionAttach the
PlayerMovementController
andNPCMovementController
to the appropriate gameObjectsDrag & Drop the components attached step 5 into the public field of the
Character
class
Interface
Create an interface called
IMovementController
declaring a single functionMove( Character character )
In the
Character
class, declare aprivate IMovementController MovementController
In the
Character
's class, makeUpdate
aprotected virtual
function callingMovementController.Move( this )
Create two other classes :
PlayerMovementController : IMovementController
andNPCMovementController : IMovementController
implementing theMove
functionAttach the
PlayerMovementController
andNPCMovementController
to the appropriate gameObjectsRetrieve the
MovementController
component in theAwake
function usingGetComponent<IMovementController>
Thank you very much! I didn't think that I can make Update() virtual and overwrite it. But it makes sense.
I love interfce implementations so I will give this a try.