Design Patterns Unity3d?

Asked

Viewed 48 times

2

Good morning,

I started working with Unity3D, everything was going well, until I saw my codes become GIANTS, so I decided to separate everything well in a design pattern ""I created three layers to separate the scripts. Model, to model the GameObjects.

public class PlayerModel {
    public GameObject PlayerGameObject { get; set; }

    public string Name { get; set; }
    public int Life { get; set; }

    public PlayerMode() { 
        this.PlayerGameObject = GameObject.FindGameObjectWithTag("Player"); 
    }
}

public class PlayerService {
    private PlayerModel playerModel;

    void recoveryLife(int quantity) {
        playerModel.Life += quantity;
    }

    public PlayerService(PlayerModel _playerModel) {
        this.playerModel = _playerModel; 
    }
}

public class PlayerController : MonoBehaviour{
    public GameObject player;
    public PlayerModel playerModel;
    public PlayerService playerService;

    void Start() {
        playerModel = new PlayerModel();
        playerModel.Name = "Personagem";
        playerModel.Life = 100;

        playerService = new PlayerService(playerModel);
    }
}

Services, to do the actions of GameObject (attack, take damage, walk, etc.) and a Controller, that makes the call of both. However, to my understanding, the controllers may be aware of another GameObject, however the model and the service can only know about themselves?

In short, someone would have some tutorial, example Design Pattern for Unity?

Thank you!

  • It’s a little hard to judge without having a more concrete view of what you were modeling. If your codes have become giant, there is a possibility that you are not using Object Orientation itself in the proper way. Did you have a lot of code snippets? Was there potential for any inheritance? These are questions that can help you.

  • The idea of the layers may be good or not. Again, it depends on what you’re modeling. Making references between objects in the Model and objects in Services (so actions can be invoked in them) also has its cost, mainly because many of the basic Unity API actions are directly related to Gameobject (collisions, for example). Depending on the game, this Services -> Model indirect can be an unnecessary cost.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.