# 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](https://utdallas.box.com/s/45539ibe840fnscj8igwgltpqipvywrf)<br>

**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](https://utdallas.box.com/shared/static/egch790793whzgdiaeahtv3kx2r5573n.unitypackage)

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.

![ChoicePanel Version 1](https://2944698967-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M0-KLgOacVpbicrqehO%2F-M3liecQsDd-sdI8DHBq%2F-M3mBDWOGB1kGuq8B3-J%2FScreen%20Shot%202020-03-31%20at%203.02.46%20PM.png?alt=media\&token=9104ab55-4386-4360-8ffe-d8dbf2e0f74b)

Both panels should have Canvas-Group Components, and The [Hide\_Show\_Panel](https://kdoore.gitbook.io/cs2335/master_v2/project-2-dialog/hideshow-panel-script) 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.](https://kdoore.gitbook.io/cs2335/master_v2/project1-code/gamedata)  The modified GameData.cs code is included at the bottom of this page.

![ChoicePanel Version 2](https://2944698967-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M0-KLgOacVpbicrqehO%2F-M3qK1Febyn-k1uEUDY1%2F-M3qUGmjpU7pJY0EJE7G%2FScreen%20Shot%202020-04-01%20at%2011.04.12%20AM.png?alt=media\&token=56a8d50f-c42a-48d8-9edc-96f5fff9be6d)

![ChoicePanel Version2](https://2944698967-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M0-KLgOacVpbicrqehO%2F-M3qK1Febyn-k1uEUDY1%2F-M3qULni1cHs9ZO-NOfW%2FScreen%20Shot%202020-04-01%20at%2011.04.28%20AM.png?alt=media\&token=4c374a94-8978-402c-8ce9-e206e73bf926)

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 &#x20;

#### Displays the Dictionary value for the specified key

![](https://2944698967-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M0-KLgOacVpbicrqehO%2F-M3qK1Febyn-k1uEUDY1%2F-M3qVt6RTMt0-hJ0nWbT%2FScreen%20Shot%202020-04-01%20at%2011.11.36%20AM.png?alt=media\&token=d5f02fa2-4346-4762-8c0c-d17f36e26c79)

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.&#x20;

![](https://2944698967-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M0-KLgOacVpbicrqehO%2F-M3mMlWmF08FoBOvfeNW%2F-M3mRGwoESVv2QHtGiFR%2FScreen%20Shot%202020-03-31%20at%204.10.55%20PM.png?alt=media\&token=500bd58b-17dc-4fc5-adac-a6d3ce8441aa)

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

![Button with SaveChoice Script with Key,Value fields](https://2944698967-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M0-KLgOacVpbicrqehO%2F-M3mMlWmF08FoBOvfeNW%2F-M3mNa5210RXstuv9Gg-%2FScreen%20Shot%202020-03-31%20at%203.56.42%20PM.png?alt=media\&token=76ff629b-66ea-491e-a5c1-ec4387d0a6d0)

#### 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

```
