Unity中按E键切换人机形态时Else语句失效问题求助
问题根源与解决方案
你的猜测完全正确——问题出在脚本挂载的对象被禁用了:
如果MechaSummoner脚本是挂在人类角色character对象上的,当你调用character.SetActive(false)后,这个GameObject被禁用,其身上所有脚本的Update()方法都会停止执行,自然无法检测到第二次按下E键的输入,所以切回人类的逻辑根本没机会触发。
修复步骤
1. 迁移脚本到永久激活的对象
创建一个空的GameObject(比如命名为GameManager),把MechaSummoner脚本从人类角色上移到这个空对象上,确保这个对象始终处于激活状态(不要在任何逻辑里禁用它)。
2. 修正代码冗余
你的ExitMecha()方法里已经写了character.SetActive(true),所以Update分支里的重复调用可以删掉,避免不必要的操作。
修改后的完整代码
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MechaSummoner : MonoBehaviour { public GameObject character; public GameObject mechaPrefab; public Transform summonPoint; public KeyCode summonKey = KeyCode.E; private GameObject mechaInstance; public bool isInMecha = false; void Update() { if (Input.GetKeyDown(summonKey)) { if (!isInMecha) { SummonMecha(); } else { ExitMecha(); } } } void SummonMecha() { mechaInstance = Instantiate(mechaPrefab, summonPoint.position, summonPoint.rotation); character.SetActive(false); character.GetComponent<CharacterController>().enabled = false; mechaInstance.GetComponent<MechaController>().enabled = true; isInMecha = true; } void ExitMecha() { Destroy(mechaInstance); character.SetActive(true); character.GetComponent<CharacterController>().enabled = true; isInMecha = false; } }
额外注意事项
- 确认
summonPoint的位置设置合理,避免机甲生成在穿墙或卡模的位置 - 测试时可以在
Update()里添加Debug.Log(isInMecha),实时查看状态是否正确切换 - 确保
MechaController和CharacterController的引用没有问题,避免空指针报错
内容的提问来源于stack exchange,提问作者ArfanMaulana
相关产品推荐
相关产品推荐

