Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*Oof, that's a tricky one :D
- Basically there are tons of ways to handle that.
- There are some builtin tools that might help you:
- - UnityAction
- Register listeners to certain actions like */
- myInventory.onItemAdded.AddListener(() => {
- DoSomeStuff();
- })
- /* - Singletons, static classes/variables/methods and ScriptableObjects
- Usefull to keep important data in a single place (I often use Singletons managers like InventoryManager, HotbarManager...). Then you can simply expose some UnityActions (onDataUpdated, onStuffDeleted, onItemCreated...) so your different scripts can listen to those events. */
- // Exemple. Creation of an item that will be displayed in the player inventory
- // Somewhere in your code
- InventoryManager.instance.CreateItem("Shovel", icon, quantity);
- // inside InventoryManager (which manage the DATA and call another manager to manage the UI)
- public Item CreateItem(string name, Sprite icon, int quantity) {
- Item item = new(name, icon, quantity);
- items.Add(item);
- // Add it to the UI through another manager
- ItemSlot itemSlot = UIInventoryManager.instance.CreateInventorySlot(item);
- item.onQuantityChange.AddListener(() => { // When the quantity of the item change
- // UIInventoryManager.instance.UpdateQuantity(itemSlot);
- // You can do that, or more simply (depending on how often those events happen):
- UIInventoryManager.instance.RefreshUI();
- })
- }
- /* In this exemple I have two managers. One to manage the data in a single place (InventoryManager) and one to manage the player inventory UI (UIInventoryManager). This basically works like a Redux store I think: all my data are in one place and my different components can listen to changes in this source of truth.
- Just like in webdev, I always try to isolate completly the UI from the data layers.
- An advantage of Unity is also that you might not need all that. Sometimes it's easier to just get the data from a static class to get the values in real-time: */
- MyStaticInventoryClass.GetAllMyItems() // returns MyStaticInventoryClass.myItems (List<Item>)
- /* There's no need to register to "a store" in some cases (like you don't need an UI that's kept in sync for a sign that would tell you "You have x shovels" when you "talk" to it). Just grab the data where it's at. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement