我目前正在开发一个2d自上而下的RPG游戏在团结。我正在尝试实现一个治疗系统,在你买咖啡的时候,你可以治愈一些问题。这是我的healthManager:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HealthManager : MonoBehaviour
{
public int maxHealth = 10;
public int currentHealth;
public HealthBarScript healthBar;
void Start()
{
currentHealth = maxHealth;
healthBar.SetMaxHealth(maxHealth);
}
void Update()
{
if(Input.GetKeyDown(KeyCode.Space))
{
TakeDamage(1);
}
}
public void TakeDamage(int damage)
{
currentHealth -= damage;
healthBar.SetHealth(currentHealth);
if(currentHealth <= 0)
{
currentHealth = 0;
}
}
public void heal(int heal)
{
currentHealth += heal;
healthBar.SetHealth(currentHealth);
if(currentHealth >= maxHealth)
{
currentHealth = maxHealth;
}
}
}这是从游戏对象(某物)购买咖啡的剧本。就像治疗喷泉):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class KaffeeautomatDialog : MonoBehaviour
{
public GameObject dialogBox;
public Text dialogText;
public string dialog;
public bool playerInRange;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.E) && playerInRange)
{
if(dialogBox.activeInHierarchy)
{
dialogBox.SetActive(false);
}
else
{
dialogBox.SetActive(true);
dialogText.text = dialog;
}
}
}
public void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
Debug.Log("Player entered");
playerInRange = true;
var healthManager = other.GetComponent<HealthManager>();
if(Input.GetKeyDown(KeyCode.J) && playerInRange)
{
if(healthManager != null)
{
healthManager.heal(5);
Debug.Log("You healed 5 Points!");
}
}
}
}
public void OnTriggerExit2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
Debug.Log("Player left");
playerInRange = false;
dialogBox.SetActive(false);
}
}
}对话框显示得很好,文本也会显示出来。当我站在疗愈喷泉前时,我可以按"e“键激活和关闭对话框。但是当我按下"j“键时,我不会痊愈,console.log也不会出现在”统一“中。
我把组件导入搞砸了吗?
发布于 2022-11-16 12:06:11
检查输入时,它应该总是发生在Update()方法中,而不是在OnTriggerEnter2D()中,因为OnTriggerEnter2D()方法只在每次触发时执行,而触发器可能只发生一次。另一方面,Update()将执行每一个帧并检查输入。
您可以做的是,在您的OnTriggerEnter2D()方法中,需要有一个全局布尔变量,该变量指示播放机已进入触发器,在检查输入键"J“时,需要在Update()方法中检查上述布尔标志是否为真,如果为真,则继续进行恢复过程。另外,当玩家退出触发器时,您需要将标志设置为false。
根据我所看到的,您已经有了这样的标志playerInRange,您可以编写以下代码:
public HealthManager healthManager;
void Update()
{
if(playerInRange)
{
if(Input.GetKeyDown(KeyCode.E))
{
if(dialogBox.activeInHierarchy)
{
dialogBox.SetActive(false);
}
else
{
dialogBox.SetActive(true);
dialogText.text = dialog;
}
}
if(Input.GetKeyDown(KeyCode.E))
{
if(healthManager != null)
{
healthManager.heal(5);
Debug.Log("You healed 5 Points!");
}
}
}
}
public void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
Debug.Log("Player entered");
playerInRange = true;
healthManager = other.GetComponent<HealthManager>();
}
}从OnTriggerEnter2D()方法中删除输入检查。
https://stackoverflow.com/questions/74459988
复制相似问题