问题描述
我有一个保存对话文本的方法,然后调用另一个将文本写到UI文本框中的方法。如果我有一个按钮,这可以正常工作。但是,我希望它在场景第一次加载时发生,但是因为我要离开场景并回到同一游戏中,所以我不想欢迎玩家回到他们每次离开时都离开的场景重新进入。
button => method =>另一个方法写入UI文本框
在开始时没有按钮怎么办?
[System.Serializable]
public class DialogueTrigger : MonoBehavIoUr
{
public Dialogue dialogue; // array of strings past in
public void Start()
{
FindobjectOfType<DialogueManager>().StartDialogue(dialogue); //find the dialogue manager and plays the startdialogue method I suppose,should do this once the script is loaded because it is the start method
}
using UnityEngine;
using UnityEngine.UI;
public class DialogueManager : MonoBehavIoUr
{
private Queue<string> sentences;
public Text dialogueText;
void Start() // dialogue manager turns sentences into queue for the sentence input into dialogue manager
{
sentences = new Queue<string>();
}
public void StartDialogue(Dialogue dialogue)
{
//sentences.Clear(); // clears sentences
foreach (string sentence in dialogue.sentences) //each "sentence in the dialogue goes through and enters the queue one by one
{
sentences.Enqueue(sentence);
}
displayNextSentence(); //display next sentence method is called once all sentences are in the queue
}
public void displayNextSentence()
{
if(sentences.Count == 0) //once there are no sentences left (queue or otherwise?) the end dialogue method is called
{
EndDialogue(); //prints out that the queue has ended... ok
return; // this return is what really ends the dialogue
}
string sentence = sentences.Dequeue(); //new sentence for sentences that are being dequeued...
dialogueText.text = sentence; //dialogue text is supposed to be the same as the sentence that was just dequeued and this should print out to whatever text was assigned to the variable dialogue text
}
感谢您阅读我的问题。
解决方法
您应该使用DontDestroyOnLoad。创建一个名为DialogueTrigger
的新脚本。然后将其附加到场景中的空白GameObject
。
using UnityEngine;
using System;
public class DialogueTrigger : MonoBehaviour
{
// Array of strings past in
public Dialogue dialogue;
public void Start()
{
// Keeps the gameobject alive on scene changes
DontDestroyOnLoad(gameObject);
// Find the dialogue manager and plays the start dialogue
FindObjectOfType<DialogueManager>().StartDialogue(dialogue);
}
}