Advertisement
Beldir

Listeners

May 22nd, 2024
462
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.26 KB | Gaming | 0 0
  1. /*Oof, that's a tricky one :D
  2.  
  3. Basically there are tons of ways to handle that.
  4.  
  5. There are some builtin tools that might help you:
  6.  
  7. - UnityAction
  8.  
  9. Register listeners to certain actions like */
  10.  
  11. myInventory.onItemAdded.AddListener(() => {
  12.     DoSomeStuff();
  13. })
  14.  
  15. /* - Singletons, static classes/variables/methods and ScriptableObjects
  16.  
  17. 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. */
  18.  
  19. // Exemple. Creation of an item that will be displayed in the player inventory
  20.  
  21. // Somewhere in your code
  22. InventoryManager.instance.CreateItem("Shovel", icon, quantity);
  23.  
  24. // inside InventoryManager (which manage the DATA and call another manager to manage the UI)
  25. public Item CreateItem(string name, Sprite icon, int quantity) {
  26.     Item item = new(name, icon, quantity);
  27.     items.Add(item);
  28.  
  29.     // Add it to the UI through another manager
  30.     ItemSlot itemSlot = UIInventoryManager.instance.CreateInventorySlot(item);
  31.     item.onQuantityChange.AddListener(() => { // When the quantity of the item change
  32.         // UIInventoryManager.instance.UpdateQuantity(itemSlot);
  33.         // You can do that, or more simply (depending on how often those events happen):
  34.         UIInventoryManager.instance.RefreshUI();
  35.     })
  36. }
  37.  
  38. /* 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.
  39.  
  40. Just like in webdev, I always try to isolate completly the UI from the data layers.
  41.  
  42. 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: */
  43.  
  44. MyStaticInventoryClass.GetAllMyItems() // returns MyStaticInventoryClass.myItems (List<Item>)
  45.  
  46. /* 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