【问题标题】:Unity Triggering a Method Once Only at the Beginning of the GameUnity 仅在游戏开始时触发一次方法
【发布时间】:2021-02-13 10:34:55
【问题描述】:

我想在我的统一游戏开始时显示对话文本作为介绍性叙述。

我有一个保存对话文本的方法,然后调用另一个将文本写入 UI 文本框的方法。如果我有一个按钮,这很好用。但是,我希望在第一次加载场景时发生这种情况,但是因为我要离开场景并在同一个游戏中返回,所以我不想每次都欢迎玩家回到他们刚刚离开的场景重新输入。

按钮 => 方法 => 另一个方法写入 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
    }

感谢您阅读我的问题。

【问题讨论】:

    标签: unity3d user-interface triggers dialog


    【解决方案1】:

    您应该使用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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-05-28
      • 2023-01-30
      • 1970-01-01
      • 2011-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-01
      • 1970-01-01
      相关资源
      最近更新 更多