Advertisement
ChrisTutorials

ExchangeMoney in C#

Mar 24th, 2023 (edited)
686
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.96 KB | None | 0 0
  1.  
  2. // Keeps track of other inventories within collider2D trigger area
  3. // Can exchange money with other inventory by calling TradeMoney when another inventory
  4. // is within the area
  5. public class Inventory {
  6.  
  7.     public int money = 0;
  8.  
  9.     void OnTriggerEnter2D(Collider2D collider) {
  10.         // Store reference to inventory within area
  11.         Inventory otherInventory = collider.GetComponent<Inventory>();
  12.  
  13.         if(otherInventory != null) {
  14.             connectedInventory = otherInventory;
  15.         }
  16.     }
  17.    
  18.     void OnTriggerExit2D(Collider2D collider) {
  19.         // Remove reference to leaving inventory
  20.         Inventory otherInventory = collider.GetComponent<Inventory>();
  21.  
  22.         if(otherInventory != null) {
  23.             connectedInventory = null
  24.         }
  25.     }
  26.  
  27.     public bool TradeMoney(int amount) {
  28.         if(connectedInventory) {
  29.             connectedInventory.money += amount;
  30.             money -= amount;
  31.        
  32.             // Success
  33.             return true;
  34.         } else {
  35.             // No connected inventory found so can't trade money
  36.             return false;
  37.         }
  38.     }
  39.  
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement