c# - 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);
}
}
解决方案
我知道上面的评论已经注意到你的问题是局部变量,多亏了他们,但这只是为了优化你的代码和内存。你可以只保留 OnTriggerEnter 并删除 Start。
private void OnTriggerEnter(Collider other)
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
如果我们不再需要使用,则无需将场景存储在变量中。这只会浪费内存(坏习惯)
推荐阅读
- typescript - 具有特定泛型类型参数的泛型函数的参数类型,在打字稿中
- python - Discord Python Bot:改变状态
- python-3.x - 使用python从文本中打印匹配的字符串后的第n行
- dolphindb - 如何在已建立的流表中添加列?
- c++ - 迭代除当前对象之外的所有其他对象
- javascript - 在springboot中用manytomany管理两个代码类的联合
- vba - 我应该怎么做才能修复错误 - 查询表达式中的语法错误(缺少运算符)?
- c++ - 如何访问 STL Stack C++ 中的结构属性?
- database - AWS RDC - Sql 开发人员,无法连接
- php - 设置工艺 cms 时获得许可被拒绝