将Unity场景中的bool值保存到另一个场景

3

我试图制作一个冒险游戏,它保存不同的布尔值以便进入下一个场景。问题是另一个场景中有一个布尔值使其为null。 有什么建议吗?

public class Farmer : MonoBehaviour
{
    public bool NextLevel = false;
    public Cow1 cow1;
    public Cow2 cow2;
    public Cow3 cow3;
    public Dialogue dialogue;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (GetComponent<Cow1>().getIsDisplayed() && GetComponent<Cow2>().getIsDisplayed() && GetComponent<Cow3>().getIsDisplayed())
        {
            NextLevel = true;
        }
        if (NextLevel == true)
        {
            FindObjectOfType<DialogueManager>().startDialogue(dialogue);
        }
    }
}
2个回答

1

是的,有一种非常简单的方法可以实现这个功能,只需给游戏对象添加 DontDestroyOnLoad 属性即可。

{
    public bool NextLevel = false;
    public Cow1 cow1;
    public Cow2 cow2;
    public Cow3 cow3;
    public Dialogue dialogue;
    // Start is called before the first frame update
    void Start()
    {
         DontDestroyOnLoad(this.gameObject); 
    }

    // Update is called once per frame
    void Update()
    {
        if (GetComponent<Cow1>().getIsDisplayed() && GetComponent<Cow2>().getIsDisplayed() && GetComponent<Cow3>().getIsDisplayed())
        {
            NextLevel = true;
        }
        if (NextLevel == true)
        {
            FindObjectOfType<DialogueManager>().startDialogue(dialogue);
        }
    }
}

这将使你的游戏对象在场景切换时保持不变。

1
请记住确保只有一个这样的实例存在。如果此脚本附加到场景A上的对象,并在场景A和B之间来回切换,则每次都会添加一个新实例。因此,Start方法应检查是否已经存在此类实例,并销毁任何新创建的实例。这是某种单例模式。 - fafase

0

您可以利用多场景编辑,使得一些值和变量在场景之间保持不变。您可以在这里了解更多相关信息。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接