我目前正在 Unity 中開發一款 2d 自上而下的 RPG 游戲。我正在嘗試實施一個治療系統,在該系統中,您可以在購買咖啡時治愈一些點。這是我的健康管理器:
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 也不會出現在 Unity 中。
我弄亂了組件匯入嗎?
uj5u.com熱心網友回復:
檢查 Input 它應該始終發生在Update()
方法內部而不是內部,OnTriggerEnter2D()
因為 OnTriggerEnter2D() 方法只會在每次某些東西進入觸發器內部時執行,這可能只發生一次。另一方面Update()
,它將在每一幀執行并檢查輸入。
您可以執行以下操作,在您的OnTriggerEnter2D()
方法中,您需要有一個全域布爾變數,指示玩家已進入觸發器,并且在您的Update()
方法中,當您檢查輸入鍵“J”時,您需要檢查上面的布林值是否標志為真,如果為真則繼續修復程序。當玩家退出觸發器時,您還需要將標志設定為 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://www.uj5u.com/net/536480.html
標籤:C#unity3d