IStackable - jimdroberts/FishMMO GitHub Wiki
Interface for objects that can be stacked together, such as items or resources. Provides methods for stack management and splitting.
-
bool CanAddToStack(T other)
Determines if the specified object can be added to the current stack. other (T): The object to check for stack compatibility. Returns: True if the object can be added to the stack, false otherwise.
-
bool AddToStack(T other)
Adds the specified object to the current stack if possible. other (T): The object to add to the stack. Returns: True if the object was successfully added, false otherwise.
-
bool TryUnstack(uint amount, out T stack)
Attempts to remove a specified amount from the stack, returning the split stack if successful. amount (uint): The amount to unstack. stack (out T): The resulting stack after unstacking. Returns: True if the unstack operation was successful, false otherwise.
- Implement IStackable on your item or resource class.
- Provide logic in the CanAddToStack, AddToStack, and TryUnstack methods to manage stacking behavior.
- Use the interface to allow objects to be stacked, split, or merged in inventory systems.
// Example 1: Implementing IStackable for an item
public class Item : IStackable<Item> {
public bool CanAddToStack(Item other) {
// Check compatibility
return true;
}
public bool AddToStack(Item other) {
// Add logic
return true;
}
public bool TryUnstack(uint amount, out Item stack) {
// Unstack logic
stack = null;
return false;
}
}
// Example 2: Stacking items in inventory
if (item1.CanAddToStack(item2)) {
item1.AddToStack(item2);
}
- Always implement all methods to handle stacking, merging, and splitting logic for your object.
- Use IStackable for all items or resources that should support stacking in inventory or world systems.
- Validate compatibility in CanAddToStack before merging stacks to prevent errors.