I made a simple survey from a guide on YouTube.
The trouble is that dropdowns are not mentioned in there, and I have totally no idea how to get the selected text value from it.
I tried multiple options, but they don't work for me, even if the compiler doesn't return any errors. Maybe the thing is that I'm implementing the code in wrong place or I miss something different.
The solution I'll paste here looks quite logical for me and I have no idea why doesn't it work. The part of code where I tried to 'read' the dropdown value is:
else if (a.GetComponent<Dropdown>()!=null)
{
result.Answer = a.transform.GetChild(0).Find("Label").GetComponent<Text>().text;
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
using System;
public class UIScript07 : MonoBehaviour
{
public GameObject[] questionGroupArr;
public QAClass07[] qaArr;
public GameObject AnswerPanel;
void Start()
{
qaArr = new QAClass07[questionGroupArr.Length];
}
// Update is called once per frame
void Update()
{
}
public void SubmitAnswer()
{
for (int i = 0; i < qaArr.Length; i++)
{
qaArr[i] = ReadQuestionAndAnswer(questionGroupArr[i]);
}
}
QAClass07 ReadQuestionAndAnswer(GameObject questionGroup)
{
QAClass07 result = new QAClass07();
GameObject q = questionGroup.transform.Find("Question").gameObject;
GameObject a = questionGroup.transform.Find("Answer").gameObject;
result.Question = q.GetComponent<Text>().text;
if (a.GetComponent<ToggleGroup>() != null)
{
for (int i = 0; i < a.transform.childCount; i++)
{
if (a.transform.GetChild(i).GetComponent<Toggle>().isOn)
{
result.Answer = a.transform.GetChild(i).Find("Label").GetComponent<Text>().text;
break;
}
}
}
else if (a.GetComponent<Dropdown>()!=null)
{
**result.Answer = a.transform.GetChild(0).Find("Label").GetComponent<Text>().text;**
}
else if (a.GetComponent<ToggleGroup>() == null)
{
string s = "";
int counter = 0;
for (int i = 0; i < a.transform.childCount - 1; i++)
{
if (a.transform.GetChild(i).GetComponent<Toggle>().isOn)
{
if (counter != 0)
{
s = s + ", ";
}
s = s + a.transform.GetChild(i).Find("Label").GetComponent<Text>().text;
counter++;
}
if (i == a.transform.childCount - 1)
{
s = s + "";
}
}
result.Answer = s;
}
return result;
}
}
[System.Serializable]
public class QAClass07
{
public string Question = "";
public string Answer = "";
}