首页 > 解决方案 > Unity Scene 不存在,尽管它已定义?

问题描述

我正在为 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);
    }
}

标签: c#unity3d

解决方案


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

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

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


推荐阅读