【问题标题】:Unity Scene does not exist although its defined?Unity Scene 不存在,虽然它已定义?
【发布时间】:2020-08-02 08:00:24
【问题描述】:

我正在为我在 Unity 中的游戏编写死亡脚本。我在关卡下方制作了一个没有纹理的 3d 盒子,并制作了它的 Collider isTrigger = true。我现在向框添加了一个脚本,当玩家进入触发器时重新加载当前场景。它的 2 行代码,我不知道为什么,但我得到了错误:

Assets\scripts\death.cs(20,32): error CS0103: The name 'currentScene' does not exist in the current context

代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class death : MonoBehaviour
{

    void Start()
    {
        Scene currentScene = SceneManager.GetActiveScene();
    }

    private void OnTriggerEnter(Collider other)
    {
        SceneManager.LoadScene(currentScene.buildIndex);
    }
}

【问题讨论】:

  • 您在 Start 中本地定义了变量 - 您必须使其成为该类的成员
  • 然后我得到以下错误: UnityException: GetActiveScene is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start 相反。从游戏对象“死亡”上的 MonoBehaviour“死亡”调用。
  • 您需要将变量声明为成员并在Start...中赋值。这也是非常基本的C#知识,您应该通过一个好的教程而不是发布这样的基本这里的问题
  • 我已回滚您的编辑。在问题标题中添加 SOLVED 或 RESOLVED 或在问题正文中编辑解决方案是不合适的。

标签: c# unity3d


【解决方案1】:

我知道上面的 cmets 已经注意到你的问题是局部变量,感谢他们,但这只是为了优化你的代码和内存。你可以只保留 OnTriggerEnter 并删除 Start。

private void OnTriggerEnter(Collider other)
{
    SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}

如果我们不再需要使用,则无需将场景存储在变量中。这只会浪费内存(坏习惯)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-13
    • 2020-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    相关资源
    最近更新 更多