【发布时间】: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 或在问题正文中编辑解决方案是不合适的。