所以我已经按照Unity Quiz游戏的教程进行了操作,并想知道如果我希望游戏只提出最多10个问题,但问题池有20个左右,所以这是教程中的脚本,我有点编辑。
我有一个名为Game Controller的脚本
void Start()
{
dataController = FindObjectOfType<DataController>(); // Store a reference to the DataController so we can request the data we need for this round
currentRoundData = dataController.GetCurrentRoundData(); // Ask the DataController for the data for the current round. At the moment, we only have one round - but we could extend this
questionPool = currentRoundData.questions; // Take a copy of the questions so we could shuffle the pool or drop questions from it without affecting the original RoundData object
timeRemaining = currentRoundData.timeLimitInSeconds; // Set the time limit for this round based on the RoundData object
UpdateTimeRemainingDisplay();
playerScore = 0;
questionIndex = 0;
ShowQuestion();
isRoundActive = true;
}
void ShowQuestion()
{
RemoveAnswerButtons();
QuestionData questionData = questionPool[questionIndex]; // Get the QuestionData for the current question
questionText.text = questionData.questionText; // Update questionText with the correct text
for (int i = 0; i < questionData.answers.Length; i ++) // For every AnswerData in the current QuestionData...
{
GameObject answerButtonGameObject = answerButtonObjectPool.GetObject(); // Spawn an AnswerButton from the object pool
answerButtonGameObjects.Add(answerButtonGameObject);
answerButtonGameObject.transform.SetParent(answerButtonParent);
answerButtonGameObject.transform.localScale = Vector3.one;
AnswerButton answerButton = answerButtonGameObject.GetComponent<AnswerButton>();
answerButton.SetUp(questionData.answers[i]); // Pass the AnswerData to the AnswerButton so the AnswerButton knows what text to display and whether it is the correct answer
}
}
持有问题和答案的脚本
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
public class DataController : MonoBehaviour
{
public RoundData[] allRoundData;
void Start ()
{
DontDestroyOnLoad (gameObject);
SceneManager.LoadScene ("MenuScreen");
}
public RoundData GetCurrentRoundData()
{
return allRoundData [0];
}
}
答案 0 :(得分:0)
你有一堆问题,其中20个正如你所说,现在你想要随机抽出10个:
Question [] questions = GetQuestions(); // This gets all questions as array
List<Question> list = new List<Question>(questions); // turn into list
int maxAmount = 10; // Set amount of questions
for(int i = 0; i < maxAmount; i++)
{
int random = Random.Range(0, list.Count); // Random number between 0 and Count (excluded)
Question question = list[random]; // Get the question
CreateQuestion(question);
list.RemoveAt(random); // Remove it from the list, not the array
}