微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Unity仅在游戏开始时触发一次方法

如何解决Unity仅在游戏开始时触发一次方法

我想在我的统一游戏开始时显示对话文字,作为介绍旁白。

我有一个保存对话文本的方法,然后调用一个将文本写到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);
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。