C# 为什么可以';当播放机位于胸部上方时,我是否检测到按键
我试图编写一段代码,玩家对胸部的OnTriggerEvent2D做出反应,然后打开胸部清单。我有它,所以箱子是在地图上随机生成的,库存位于现场C# 为什么可以';当播放机位于胸部上方时,我是否检测到按键,c#,unity3d,C#,Unity3d,我试图编写一段代码,玩家对胸部的OnTriggerEvent2D做出反应,然后打开胸部清单。我有它,所以箱子是在地图上随机生成的,库存位于现场 using UnityEngine; using UnityEngine.SceneManagement; public class ChestInteractable : MonoBehaviour { [SerializeField] KeyCode interactableKey = KeyCode.E; //allow player t
using UnityEngine;
using UnityEngine.SceneManagement;
public class ChestInteractable : MonoBehaviour
{
[SerializeField] KeyCode interactableKey = KeyCode.E; //allow player to choose key
public GameObject chestInventoryUI;
private void OnTriggerEnter2D(Collider2D collision) //if player collides with chest (I am unsure if OnCollisionEnter2D is better, I am only a beginner)
{
if(Input.GetKeyDown(interactableKey)) {
chestInventoryUI.SetActive(true); //open up chest inventory
Time.timeScale = 0f; //time is stopped
}
if(Input.GetKeyUp(interactableKey))
{
chestInventoryUI.SetActive(false); //closes chest inventory
Time.timeScale = 1f; //time resumes
}
}
}
我试着将箱子清单移动到场景和箱子预制件。
我已经将可交互代码添加到胸部预设中,并在胸部预设中设置胸部清单时将胸部清单作为游戏对象。当库存UI位于场景中时,我无法执行此操作
using UnityEngine;
using UnityEngine.SceneManagement;
public class ChestInteractable : MonoBehaviour
{
[SerializeField] KeyCode interactableKey = KeyCode.E; //allow player to choose key
public GameObject chestInventoryUI;
private void OnTriggerEnter2D(Collider2D collision) //if player collides with chest (I am unsure if OnCollisionEnter2D is better, I am only a beginner)
{
if(Input.GetKeyDown(interactableKey)) {
chestInventoryUI.SetActive(true); //open up chest inventory
Time.timeScale = 0f; //time is stopped
}
if(Input.GetKeyUp(interactableKey))
{
chestInventoryUI.SetActive(false); //closes chest inventory
Time.timeScale = 1f; //time resumes
}
}
}
我希望胸部清单界面可见,游戏停止,但什么也没发生。Use
使用
尝试使用
void OnTriggerStay2D(碰撞r2d碰撞)
,因为您希望在有重叠的每一帧调用它。否则,玩家将不得不在重叠开始的确切帧上按下键,这不是你的意思:)我还认为在它上使用private
可能会把它搞砸,所以只需将其设置为void…
而不需要访问修改器。因此,请注意,在单个帧中可能会发生键下和键上,特别是对于延迟,因此if(input.GetKeyDown(…)
和if(input.getkeydup(…)
块最终都会被执行,因为如果关键事件发生在当前帧期间,它们都会返回true。请尝试使用void OnTriggerStay2D(碰撞r2d碰撞)
因为您希望每帧调用一次,所以存在重叠。否则,玩家将不得不在重叠开始的确切帧上按下键,这不是你的意思:)我还认为在它上使用private
可能会把它搞砸,所以只需将其设置为void…
而不需要访问修改器。因此,请注意,在单个帧中可能会发生键下和键上,特别是对于延迟,因此if(input.GetKeyDown(…)
和if(input.getkeydup(…)
块最终都可以执行,因为如果关键事件发生在当前帧期间,它们都返回true。