CS2335
Master 1.0.0
Master 1.0.0
  • Introduction
  • Introduction
    • Introduction
      • Game Design
    • Unity - Download
    • Visual Studio - IDE
    • Unity Manual, Scripting API
  • Unity Basics
    • Unity Editor Windows
    • Behavior Components
    • 2D Project, Scenes
      • Create 2D Sprite GameObject
      • Create UI-Text GameObject
    • MonoBehavior - Base-Class
    • Create a Custom C# Script
  • Game Coding Structures
    • Games Overview
    • Unity Engine - Event Functions
    • Finite State Machines
    • UML Class Diagram
  • Animation
    • Animator Controller
    • Animation Steps
      • Optional: Dead Animation
    • PlayerController.cs V0
  • Project 1 - Player
    • Player GameObject v1
      • C# Generics, Statics
    • Player GameObject - Jump
    • PlayerController.cs V2-Jump
    • PickUp PreFabs
      • Sorting Layers
    • PlayerController.cs V3-Collide
    • GameData Version1
    • GameData Version2
    • PlayerController V4-Score
  • Project 1 Details
    • Project1 GameObjects
    • PlayerStats Version1
      • UI-Canvas
    • Utility Class
    • Simple Spawner
    • MiniGameManager
      • Logic Diagrams
      • StartButton
      • ResultsPanel
  • Project1 Enhancements
    • PickUp - SelfDestruct
    • Spawn from List of Prefabs
  • Project 2 - StateManager
    • Project 2 - Learning Objectives
      • Inspiration
        • Branching Story Structures
        • Branching Structures
        • Hero's Journey
        • Visual Novel in Unity-Links
    • Project 2 - Starter Assets
    • State Machine Framework
    • StateManager - Singleton Design Pattern
    • Interface IStateBase
    • Create SceneXState.cs
    • OptionPanel Prefab
      • UI Images: Sprite Sheets
      • Button Image-Transitions
    • Project 2 - List of Steps
    • Project 2 - Starter Code
  • Project 2 -Dialogue
    • Hide_Show_Panel Script
    • Edit OptionPanel
    • Simple DialogPrefab
    • Conversation Entry
    • SimpleDialog.cs
    • ScriptableObjects
      • Scriptable Object Factory
    • Conversation Scriptable Objects
    • DialogManager_ConvList
      • DialogManager V2
      • Coroutines: Dynamic Text
      • DialogPrefab wImage
  • Overview: Branching Logic
    • DialogTrigger
    • Dictionary Data-Structure
      • Unity PlayerPrefs Dictionary
    • GameData Version3
    • Dictionary: choiceData
      • SaveChoice, ChoicePanel
        • choiceData - examples
          • Dictionary Value to Disable Options
    • Configure UI-Button Listeners
      • NPC Animation
      • NPC Activation
    • UI-Triggered Animations
    • Simple Inventory
    • EndState Conditions
    • Script ExecutionOrder
    • Custom UnityEvents
    • PlayerStats v2
      • ModifyPlayerData
      • BuyItem
    • Text Input
  • UI Components
    • Finding Game Objects
    • Game Objects: UI vs. 2D Sprite
    • UI Elements
      • Canvas: Screen-Space Render-Mode
      • UI-Buttons To Change Scene
  • Proj4: Inventory System
    • Inventory-System
      • GameData version4
      • Install and Configure
      • Diagrams, Resources
        • Item, Gem, Potion Classes
        • Inventory Class
      • InventoryDisplay, Slot UI
        • InventoryDisplay Class
        • Slot Class
        • Hazard Class
        • Layout Groups
      • Customization Steps
        • Configure Animation
        • AddItem Button
        • Concrete Class: Food
        • MiniGame Mods
          • PlayerController Mods
      • Code: InventorySystem
        • GameData, PickUp Mods
      • Resources: Data Structures
  • Custom Unity Events
    • Event Publishing Patterns
    • Custom Event Messaging
  • Proj4: Mini-Game
    • Simplified Mini-Game
      • PlayerController_v2 Mods
        • PlayerController_v2_final
      • MiniGameManager_v2
    • MiniGame-Overview-Proj4
    • LevelManager
      • LevelManager Logic Diagram
      • LevelManager FSM
      • LoadLevel, StartLevel Logic
      • Code Framework
    • Timer
  • Project 4 - Code Mods
    • Project 4 - Steps
    • Project 4 - Code
      • Code: Final Versions
        • PlayerController Mods
          • PlayerController_v2 Mods
        • GameData - Final
        • LevelManager
        • PlayerStats - Final
        • PickUp, Hazard, ScorePickUp
        • Spawner - Final
        • CameraFollow
        • ScreenFader
        • MiniGameState
        • Example: EndState
      • MiniGameWin Logic
  • Optional, Supplemental Content
    • Optional Content
      • Particle Systems
      • Adding Audio
      • Screen Fading and Reloading
      • ScriptableObjects
      • Disable Debug Logging
      • Events and Actions
      • Saving Data - Serialization
      • Parallax Scrolling
      • Change Sprites
    • XR - Extended Reality
  • Computing Concepts
    • Programming Patterns
      • State - FSM
      • Singleton Pattern
    • C# Language
      • Variables
      • Delegates
      • Dictionary
      • Enum
      • Encapsulation
        • C# Properties
        • Access Modifiers
      • Generics < T >
      • Inheritance
      • Interface
      • List< T >
      • Polymorphism
      • Queue< T >
      • Switch-Case
      • Foreach
      • Static
      • Ternary Operator: ?
      • this
    • Diagrams
      • State Machine Framework
      • UML Class Diagrams
      • Level Manager Logic Diagram
      • Flow-Chart: NumberGame
      • FSM: NumberGame
    • Tools
    • Glossary
    • References and Resources
    • Random Thoughts
Powered by GitBook
On this page
  • UI-Animation logic - Configure or Disable.

Was this helpful?

  1. Proj4: Inventory System
  2. Inventory-System
  3. InventoryDisplay, Slot UI

InventoryDisplay Class

PreviousInventoryDisplay, Slot UINextSlot Class

Last updated 5 years ago

Was this helpful?

UI-Animation logic - Configure or Disable.

The image below shows code logic in the InventoryDisplay.cs script that animates visibility of the InventoryDisplay when the user presses the Tab key. You'll need to decide to configure the animation or you must delete the associated code, or you will have errors in scenes where you use the InventoryDisplay.

To Disable Animation If you choose not to implement the UI-Animation, then you'll want to disable or remove the code associated with the Animator component otherwise, you will have errors when the the InventoryDisplay is included in a scene.

Delete the Animator declaration line of code in order to identify and disable all code associated with Animator functionality

Animator visibilityAnimator; ////DELETE THIS LINE - To disable animator

Delete or disable code with errors, shown highlighted in image below

updated Apr 11,2020

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

//modified from
////https://github.com/Toqozz/blog/blob/master/inventory

//updated 4/11/2020

public class InventoryDisplay : MonoBehaviour
{
    private List<Slot> inventorySlots;
    private Inventory inventory;
   
    public Dictionary<string, int> InstanceTypeCounts = new Dictionary<string, int>(); //dictionary

    public const int NumSlots = 4; //must change if more slots are displayed
    public int displayedRowPointer=0; //
    Animator visibilityAnimator; //comment out if animation is not used
    public bool isVisible = false;

        // Use this for initialization
    void Start()
    {
        inventory = GameData.instanceRef.inventory;

        //inventoryDisplay wants to be notified when inventory changes
        inventory.onInventoryUpdate.AddListener(UpdateDisplay);

        // find all child slots, put in a list
        inventorySlots = new List<Slot>();
        //add child slots to the inventorySlots list.
        inventorySlots.AddRange(Object.FindObjectsOfType<Slot>());

        // Maintain some order (just in case it gets screwed up).
        inventorySlots.Sort((a, b) => a.index - b.index);
        SetSlotIndexes();
        PopulateInitial();

        //comment out code below if not using animation
        visibilityAnimator = GetComponent<Animator>();
        visibilityAnimator.SetBool("IsVisible", false);
    }

    //Listen for Tab key for Animation - every frame
    private void Update()
    {
        if( Input.GetKeyUp( KeyCode.Tab))
        {
            isVisible = !isVisible;
            visibilityAnimator.SetBool("IsVisible", isVisible);
        }
    }

    //update itemCount dictionary: items, counts - get data from
    //inventory
    //condense data into key-value pairs:  item: count
    private void UpdateItemCounts()
    {
      
        InstanceTypeCounts.Clear(); 
         //for all items in the inventory's inventory list
         //count the number of items with the same InstanceType ( enum values )
         //put unique item in dictionary/ with count as value
        
        for( int i=0; i< inventory.inventory.Count; i++)
        {
            //for each item in data inventory list
            //if the inventory list element with index i
            //add key: InstanceType to dictionary, update count

            if (!inventory.SlotEmpty(i)) //is there an item in the inventory for each list item?
            {
                ItemInstance item = inventory.inventory[i]; 
                string instanceType = item.item.instanceType; //is string cast of enum value
                int count;
                if (InstanceTypeCounts.TryGetValue(instanceType, out count))
                {
                    InstanceTypeCounts[instanceType] = ++count; //if already added, increment count
                }
                else //did not find item in the dictionary, so add as key,value=1
                {
                    InstanceTypeCounts.Add(instanceType, 1); //add item
                }
            }
        }
    }

    private void PopulateInitial()
    {
        UpdateItemCounts(); //populate dictionary
        if( InstanceTypeCounts.Count > 0) { //something in the dictionary
        int index = 0;
            //get the keys (all existing items) 
             Dictionary<string, int>.KeyCollection keys = InstanceTypeCounts.Keys;

            //loop through all key-value: InstanceType-count pairs
            foreach (string instanceType in keys)
            {
                if (index < NumSlots) //fill the first 4 slots
                {
                    int value = InstanceTypeCounts[instanceType];//use current key-item to get the count (value)
                   
                     if (instanceType != null) //display slot already has an item of matching key
                    {
                        //Update the slot, by updating the count

                        //get one itemInstance from Inventory using InstanceType match?
                        ItemInstance oneItem = inventory.GetByItemType(instanceType);
                        if (oneItem != null)
                        {
                            inventorySlots[index].SetItem(oneItem, value);
                            index++; //move to next slot
                        }
                    }
                }
                else
                {
                  Debug.Log("more items than slots, some not displayed");
                }
            }
        }

    } //end method

    void SetSlotIndexes()
    {
        foreach( Slot slot in inventorySlots)
        {
            slot.index = inventorySlots.IndexOf(slot);
        }
    }

    public void RemoveItem(ItemInstance item, int index )
    {
        string itemTypeKey = item.item.instanceType; //get item's InstanceType to use as key
        int count=0;
        if(InstanceTypeCounts.TryGetValue( itemTypeKey, out count))
        {
            if( count <= 1) //if the last one
            {
                InstanceTypeCounts.Remove(itemTypeKey); //remove from dictionary itemCounts using key
                inventorySlots[index].RemoveItem(index);//remove from slot display
                inventory.RemoveOneItem(item); //remove from data inventory
            }
            else
            {
                InstanceTypeCounts[itemTypeKey] = count - 1;  //decrease dictionary count for this InstanceType
                inventorySlots[index].SetItem(item, count-1);  //update slot's displayed count value
                inventory.RemoveOneItem(item); //remove one from data inventory
            }
        }
    } //end RemoveItem(  )

    //Listener for onInventoryUpdate Event
    public void UpdateDisplay()
    {
        ClearSlots(); //clear slots
        PopulateInitial(); //reset dictionary count and slots
    }

    //Adds an item to the itemCount dictionary
    //or updates the count if item was already in the dictionary
    void AddToCounts(ItemInstance item)
    {
        int count;
        if (InstanceTypeCounts.TryGetValue(item.item.instanceType, out count))
        {
            InstanceTypeCounts[item.item.instanceType] = ++count;
            Debug.Log("itemCount " + item.item.itemName + " " + count);
        }
        else if (InstanceTypeCounts.Count <= NumSlots) //we still have an available slot
        {
            InstanceTypeCounts.Add(item.item.instanceType, 1); //add first item
        }
    }

    //clear all inventory slots
   private void ClearSlots()
    {
        for (int i = 0; i < inventorySlots.Count; i++)
        {
            inventorySlots[i].RemoveItem(i);
        }
    }

    //unregister listener when this object is destroyed 
    private void OnDisable()
    {
        inventory.onInventoryUpdate.RemoveListener(UpdateDisplay);
    }

} //end class InventoryDisplay