예제 #1
0
        /// <summary>
        /// Add a `GameObject` to the first open slot.
        /// Expects `GameObject` to have a `Draggable`
        /// component attached.
        /// </summary>
        /// <param name="item">The `GameObject` item to add to
        /// this container</param>
        public override void Add(GameObject item)
        {
            Draggable dragHandler = item.GetComponent <Draggable>();

            if (dragHandler == null)
            {
                throw new MissingComponentException("Adding to Container requires `Draggable` component");
            }

            Stackable stackHandler = item.GetComponent <Stackable>();
            Slot      emptySlot = null, stackableSlot = null;

            foreach (Slot slot in Slots)
            {
                //  retrieve the first empty slot and retain
                if (emptySlot == null && slot.Item == null)
                {
                    emptySlot = slot;

                    //  if there's an item in this slot
                    //  but the item being added is stackable
                    //  check if it can stack
                }
                else if (slot.Item && stackHandler != null)
                {
                    Stackable itemStack = slot.Item.GetComponent <Stackable>();

                    if (itemStack != null && itemStack.CanStack(stackHandler))
                    {
                        stackableSlot = slot;
                    }
                }
            }

            //  add the item to the slot
            //  will prioritize stackable slot
            if (stackableSlot != null)
            {
                stackableSlot.AddItem(dragHandler);
            }
            else if (emptySlot != null)
            {
                emptySlot.AddItem(dragHandler);
            }

            throw new NotStackableException("Unable to add item (" + dragHandler.name + ") to container ( " + name + ")");
        }