User-Choices - Example

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

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: ChoicePackage_V2

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.

Both panels should have Canvas-Group Components, and The Hide_Show_Panel 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 GameData.cs version 1. The modified GameData.cs code is included at the bottom of this page.

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

Last updated