CS2335
Master_v2
Master_v2
  • Introduction
  • Introduction
    • Introduction
      • Design
      • Game Design
    • Unity - Download
    • Visual Studio - IDE
    • Hero's Journey
  • Unity Basics
    • Unity Editor Windows
    • MonoBehavior - Base-Class
    • Unity Engine - Event Functions
  • Getting Started
    • UI-Elements
    • Animator Controller
      • Animation Steps
    • PlayerController Flow Chart
    • PlayerController Code
      • PlayerController - V1 - S20
      • PlayerController V2 S20
      • PlayerController V3 S20
  • Project 1 - Simple Game
    • Overview
    • Project 1 - Get Started
      • UML Class Diagram
    • Player GameObject
      • PlayerController.cs V2
      • PlayerController.cs V3
    • Create 2D Sprite Prefab: Rock
    • Sorting Layers
  • Project1 Code
    • PickUp PreFabs
    • Player GameObject
    • PlayerController - jump
    • GameData Version1
    • PlayerStats Version1
    • MiniGameManager
      • Logic Diagram
    • Simple Spawner
    • Utility Class
  • Project1 Enhancements
    • PickUp - SelfDestruct
    • Spawn from List of Prefabs
  • Project 2 - StateManager
    • Project 2 - Learning Objectives
    • Project 2 - Starter Assets
    • Project 2
      • State Machine Framework
        • Singleton Pattern
      • StateManager - Singleton Design Pattern
      • IStateBase, BeginState
      • Project 2 -Steps: Create new Scene and State
      • Project 2 - List of Steps
        • Project 2 - Starter Code
  • Project 2 -Dialog
    • Hide_Show_Panel Script
    • Configure TitlePanel, DecisionPanel
    • Simple Dialog Prefab
    • Conversation Scriptable Objects
    • DialogManager_ConvList
    • Image Transitions for Buttons
  • UI Components
    • Finding Game Objects
    • Game Objects: UI vs. 2D Sprite
    • UI Elements
      • Canvas: Screen-Space Render-Mode
      • UI-Buttons To Change Scene
      • Text Input
  • Project2 Resources
    • Visual Novel in Unity-Links
    • Scriptable Object Factory
      • ScriptableObjects
    • Dialog Prefab Packages
  • Project 3 - Overview
    • Branching Story Structures
    • Dictionary Data-Structure
      • Unity PlayerPrefs Dictionary
    • Dictionary: User-Choice Data
      • User-Choices - Example
        • Dictionary Value to Disable Options
    • Simplified Mini-Game
      • PlayerController_v2 Mods
        • PlayerController_v2_final
      • MiniGameManager_v2
  • Proj3: Inventory System
    • Inventory-System
      • 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
  • Proj3: Custom UnityEvents
    • Event Publishing Patterns
    • Custom Event Messaging
  • Proj3: Mini-Game
    • MiniGame-Overview-Proj3
    • LevelManager
      • LevelManager Logic Diagram
      • LevelManager FSM
      • LoadLevel, StartLevel Logic
      • Code Framework
    • Timer
  • Project 3 - Code Mods
    • Project 3 - Steps
    • Project 3 - 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
      • Adding Audio
      • Screen Fading and Reloading
      • ScriptableObjects
      • Disable Debug Logging
      • Events and Actions
      • Saving Data - Serialization
      • Parallax Scrolling
      • Change Sprites
  • C# Language
    • C# Language
      • Variables
      • Enum
      • Encapsulation
        • C# Properties
        • Access Modifiers
      • Inheritance
      • Polymorphism
      • Interface
      • Switch-Case
      • List< T >
      • Queue< T >
      • Dictionary
      • Foreach
      • Static
      • Ternary Operator: ?
      • this
      • Delegates
    • Diagrams
      • State Machine Framework
      • UML Class Diagrams
      • Level Manager Logic Diagram
      • Flow-Chart: NumberGame
      • FSM: NumberGame
    • Glossary
    • References and Resources
    • Random Thoughts
Powered by GitBook
On this page
  • ShowChoice Panel with ShowChoice.cs
  • SaveChoice.cs - Attach to each child Button

Was this helpful?

  1. Project 3 - Overview
  2. Dictionary: User-Choice Data

User-Choices - Example

PreviousDictionary: User-Choice DataNextDictionary Value to Disable Options

Last updated 5 years ago

Was this helpful?

To demonstrate a simple example of using a C# Dictionary for storing and accessing user choice data, consider the following example.

ChoicePackage Version 1 uses Images for Buttons, with a Horizontal Layout Group Unity Package with Prefab Panels, Scripts, Images: Box.com link:

ChoicePackage_V2 uses default buttons and uses 1 panel to contain all gameObjects. This version uses a Vertical Layout Group for the Panel that holds the Buttons This may be easier to use and modify. Unity Package with Prefab Panels, Scripts: Box.Com Link:

Directions for creating ChoicePackage Version 1 In BeginScene, You will create 2 UI-Panels, one holds 3 buttons, one has text to display the selected choice. In the image below we can see that for this example, we'll work with 2 panels, one to allow selecting a choice, and the other panel to display the choice. The ChoicePanel has 3 child buttons to allow the user to make a choice that isn't directly associated with changing scenes. This example uses images for the buttons, that's not necessary.

The general idea is that we'd like a simple script that can be attached to any Button so that clicking the Button will update the database for the key,value pair associated with the Button.

ShowChoice Panel with ShowChoice.cs

Displays the Dictionary value for the specified key

The inspector below shows that the ShowChoice Script allows the Dictionary key to be specified. This panel is hidden at start, and opens when a choiceButton has been selected.

This script can be attached to a Panel that has a CanvasGroup and a child Text element. If you add the Hide_Show_Panel.cs script to the ShowChoice panel, then it'll be hidden when the scene starts.

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

public class ShowChoice : MonoBehaviour
{
    public string key;
    public Text showText; //populate in inspector
    
    public void UpdateDisplay()
    {
        string value = GameData.instanceRef.GetChoice(key);
        showText.text = value;
        Debug.Log("show choice " + value);
    }
}

SaveChoice.cs - Attach to each child Button

Set the Key, Value pair for the SaveChoice Component

The script below is attached to a Button, and has code to be executed when the Button is clicked, so first we have to find the Button Component in Start, this is a bit of a work-around. When one of the Buttons is clicked, it updated the Dictionary in GameData. Then it finds it's parent and gets the CanvasGroup of the parent and hides the entire panel. Then it checks to see if the parent panel has an attached Hide_Show_Panel script with a nextPanelToOpen. It opens that panel and checks to see if there is a ShowChoice script on that Panel, if so, it executes: UpdateDisplay( ). See code for that script below.

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

public class SaveChoice : MonoBehaviour
{
    [SerializeField]
    string key, value; //set in inspector for each Button

    GameObject parentGameObject;
  
    Button thisItem;
    // Start is called before the first frame update
    private void Start()
    {
        thisItem = GetComponent<Button>();
        thisItem.onClick.AddListener(OnChoiceSelected);
    }

    public void OnChoiceSelected()
    {
        GameData.instanceRef.SaveChoice(key, value);
        Debug.Log("Saved Value " + GameData.instanceRef.GetChoice(key));
        thisItem.Select(); //show Button selected Image

        //Find Parent Panel and set interactible 
        parentGameObject = this.transform.parent.gameObject; //find parent
        CanvasGroup parentCG = parentGameObject.GetComponent<CanvasGroup>();
        Utility.HideCG(parentCG); //hide the choice panel
        UpdateShowNextPanel( parentCG );
        }

    /// <summary>
    /// If using a nextPanelToOpen with child Text to update:
    /// Updates the ShowChoice Text, and ShowCG for the ChoicePanel's CG
    /// </summary>
    /// <param name="parentCG">Parent cg.</param>
    void UpdateShowNextPanel( CanvasGroup parentCG)
    {
        Hide_Show_Panel hs_Component = parentCG.GetComponent<Hide_Show_Panel>();
        if (hs_Component.nextPanelToOpen != null)
        {
            //Get ShowChoice component that's on the showChoicePanel we've just found
            ShowChoice showChoice = hs_Component.nextPanelToOpen.GetComponent<ShowChoice>();
            if (showChoice != null)
            {
                showChoice.UpdateDisplay(); //updates the text, data accessed from the Dictionary
                Debug.Log("call ShowChoice.updateDisplay");
            }
            Utility.ShowCG(hs_Component.nextPanelToOpen);
        }
    }
}//end class

GameData v2; Code added for choiceData Dictionary<string, string>

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

/// <summary>
/// Singleton Object to store all GameData
/// Is not destroyed when changing scenes
/// </summary>
public class GameData : MonoBehaviour
{
    public static GameData instanceRef; //null //variable that can point to a GameData object

    private int totalScore;
    private int health;
    private int levelScore; //project 3

    private Dictionary<string,string> choiceData = new Dictionary< string,string>();
    /// <summary>
    /// Properties - provide read/write access to variables
    /// </summary>

    public int TotalScore
    {
        get { return totalScore; } //Read access
                                   // set { totalScore = value; }   //write access
    }

    public int Health
    {
        get { return health; } //read-only acccess
    }

    // Awake is called before Start() is called on any GameObject
    // Other objects have dependencies on this object so it must be created first
    void Awake()
    {
        if (instanceRef == null)  //this code hasn't been executed before
        {
            instanceRef = this; //point to object instance currently executing this code
            DontDestroyOnLoad(this.gameObject); //don't destroy the gameObject this is attached to
        }
        else  //this object is not the first, it's an imposter that must be destroyed
        {
            DestroyImmediate(this.gameObject);
            Debug.Log("Destroy GameData Imposter");
        }

        //initialize after destroying imposters
        totalScore = 0;
        health = 100;
        levelScore = 0;

    } //end Awake

    //will be executed in PlayerController when colliding with a collectible
    public void Add(int value)
    {
        totalScore += value;
        Debug.Log("Score updated: " + totalScore); //display score in console
    }

    public void TakeDamage(int value)
    {
        health -= value;
        Debug.Log("health updated: " + health); //display health in console
        if (health <= 0)
        {
            Debug.Log("Health less than 0"); //display health in console

        }
    }

    public void SaveChoice( string choiceKey, string choiceValue)
    {

        if (choiceData.ContainsKey(choiceKey))
        {
            choiceData[choiceKey] = choiceValue; //change stored value
            Debug.Log("Choice Changed" + choiceKey + " : " + choiceValue);
        }
        else
        {
            choiceData.Add(choiceKey, choiceValue); //adds key,value pair
            Debug.Log("Choice Data Created" + choiceKey + " : " + choiceValue);
        }
    }

    public string GetChoice( string choiceKey)
    {
        string choiceValue = "None";
        choiceData.TryGetValue(choiceKey, out choiceValue);
        Debug.Log("Choice Data Accessed" + choiceKey + " : " + choiceValue);
        return choiceValue;
    }

    //called when restarting the miniGame
    public void ResetGameData()
    {
        totalScore = 0;
        health = 100;
    }


}//end class GameData

Both panels should have Canvas-Group Components, and The Script attached. ( if you haven't created Hide_Show_Panel script before, do it now) This script gives options in the inspector for any panel with a CanvasGroup that allows for easy configuration of having a panel opened or closed by a button, when this script is added to a panel, it will be hidden on start by default.

Scripts: Both examples use 2 new scripts: SaveChoice.cs, and ShowChoice.cs and includes changes to The modified GameData.cs code is included at the bottom of this page.

Hide_Show_Panel
GameData.cs version 1.
ChoicePackage
ChoicePackage_V2
ChoicePanel Version 1
ChoicePanel Version 2
ChoicePanel Version2
Button with SaveChoice Script with Key,Value fields