Hi everyone,
Since a while, I have tried to figure out how to keep my code clean and easy to change with many linked classes. Here is my problem.
I have an InteractionController class, a Player class, an Inventory class and an Equipment class.
What I would like to do is, the InteractionController trigger an intraction like a pickup item on ground. This is send to the player to add it to its inventory. Before adding it, he must check if it won’t be too heavy for him to carry this new item or these new items. So he asks for the inventory its total weight and the same for the equiment. If the addition of the current weight of both and the new items is under his limit, he adds it to its inventory.
My question here is, I have seen both of these videos Connecting scripts on the same object in Unity & Breaking up Code in Unity (Important game dev tips for beginners) and many others.
They look pretty good, I tried to replicate the second one by breaking up my player into fewer scripts like the InteractionController, Inventory, Equipment which are all Monobehaviour classes.
But with what I want to do, it seems that I must write a new function into the player class to add an item to its inventory and make all the validation steps to see if it is possible or not.
Here is a quick overview of what I have in mind, does it seem correct to you. I am scared of using this method because of the spaghetti code mentioned many times. I really would like to get your opinion on this.
public class InteractionController : MonoBehaviour
{
Player player;
public void Interact(GroundObject groundObject)
{
player.AddToInventory(groundObject.Item, groundObject.Amount);
}
}
public class Player : MonoBehaviour
{
float maxWeight;
Inventory inventory;
Equipment equipment;
public void AddToInventory(Item item, int amount)
{
if (item.Weight * amount + inventory.GetTotalWeight() + equipment.GetTotalWeight() < maxWeight)
inventory.AddToInventory(item, amount);
}
}
public class Inventory : MonoBehaviour
{
public void AddToInventory(Item item, int amount)
{
}
public float GetTotalWeight()
{
return totalWeight;
}
}
public class Equipment : MonoBehaviour
{
public float GetTotalWeight()
{
return totalWeight;
}
}