I am developing a FPS in Unity.
How can I prevent the player from picking up recovery items when the player's HP is 100 (full)? Currently, players can pick up recovery items even when their HP is full, and I want to limit the conditions for getting them. The first thing I can think of is to temporarily disable the collision on the recovery item side, when the player's HP is 100.
I want to use collider.enabled = false; in an if statement, how do I write it?
Or am I doing it wrong?
Please surpport me.
HPItem.cs (This is a HPItem)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HPItem : MonoBehaviour
{
public FPSController fPSController;
public int reward = 100;
public AudioClip getSound;
<summary>
</summary>
<param name="collision"></param>
[SerializeField]
public Vector3 speed;
void Start()
{
fPSController = GameObject.Find("Player").GetComponent<FPSController>();
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Player")
{
AudioSource.PlayClipAtPoint(getSound,transform.position);
Destroy(gameObject, getSound.length);
fPSController.AddHP(reward);
}
}
}
FPSController.cs(This is a Player)
int playerHP = 100, maxPlayerHP = 100;
public Slider hpBer;
public void AddHP(int amount)
{
playerHP = amount;
if (playerHP > 100)
{
playerHP = 100;
}
}
CodePudding user response:
It would not be better to check the onTriggerEnter function, once you know that it is the player you check the value of life, if it is 100 you do not collect it
CodePudding user response:
Check the health of the player when the collision happens, only collect if health is not full.
Not a perfect solution (i.e. if player loses health while standing on the health item, they won't pick it up), but you could use OnTriggerStay() for that.
FPSController.cs:
// Add public getter for heath
public int Health => playerHP;
HPItem.cs:
...
void OnTriggerEnter(Collider other)
{
// Add check for health to this if statement.
// && statements are evaluated left to right, so
// no danger of NullReferenceException
if (other.gameObject.tag == "Player" &&
other.GetComponent<FPSController>().Health != 100)
{
AudioSource.PlayClipAtPoint(getSound,transform.position);
Destroy(gameObject, getSound.length);
fPSController.AddHP(reward);
}
}
...
