Hi there,
I am trying to add a health pickup system for my laser defender game. I managed to pickup the pill within the scene with this newly created HealthPickup class
using UnityEngine;
public class HealthPickup : MonoBehaviour
{
[SerializeField] int healAmount = 30;
private void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
Player player = other.GetComponent<Player>();
if (player != null)
{
Health playerHealth = player.GetComponent<Health>(); // Get the Health component from the player
if (playerHealth != null)
{
playerHealth.Heal(healAmount); // Pass maxHealth from the Health component
Destroy(gameObject);
}
}
}
}
}
but when I update this class to spawn the health pickup object by default when the player’s health reduces to 10%
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HealthPickup : MonoBehaviour
{
[SerializeField] int healAmount = 30;
[SerializeField] float despawnTime = 10f; // Time in seconds before the pickup disappears
private bool isActive = false;
private float spawnTime;
void Start()
{
Health playerHealth = FindObjectOfType<Player>().GetComponent<Health>();
if (playerHealth != null)
{
float healthPercentage = (float)playerHealth.GetHealth() / playerHealth.maxHealth;
if (healthPercentage < 0.1f)
{
isActive = true;
spawnTime = Time.time;
}
}
}
private void Update()
{
if (isActive && Time.time - spawnTime > despawnTime)
{
Destroy(gameObject);
}
}
private void OnTriggerEnter2D(Collider2D other)
{
if (isActive && other.CompareTag("Player"))
{
Player player = other.GetComponent<Player>();
if (player != null)
{
Health playerHealth = player.GetComponent<Health>();
if (playerHealth != null)
{
playerHealth.Heal(healAmount);
Destroy(gameObject);
}
}
}
}
}
I get this compiling error " Assets\Scripts\HealthPickup.cs(19,85): error CS0122: ‘Health.maxHealth’ is inaccessible due to its protection level"
I am trying to add this feature to the game but it seems I went way over my head and feeling frustrated as a total noob Could you please have a look and share some wisdom about how to create this setup for my game?
Thanks in advance