- Home /
Health Pickup is Not Working
Hello, I'm having this weird problem where my main health script doesn't want to pick up a bool from another script. Or at least I think that's the problem. Basically, I have this health pickup that detects when the player is colliding with it. And when it does, it sets a bool in itself to true for a few frames. Then it deletes itself. The global player health script is supposed to take the variable from that script and use it to add health. But it doesn't do anything at all when the bool is set to true. So uh, I guess I'll put some code below.
//This is the health pickup segment in the main player health script
#region Health Pickups
//Initializing Variables
bool hp1 = GameObject.Find("Heart").GetComponent<HealthPickup>().Health;
//Applying Health
if (hp1 == true)
{
Health += 1;
Debug.Log("I got health!");
}
#endregion
//The whole Health Pickup Script
using UnityEngine;
using System.Collections;
public class HealthPickup : MonoBehaviour {
bool isFull = false;
public bool Health = false;
float HP;
float maxHP;
void Update () {
HP = GameObject.Find("Player").GetComponent<PlayerHealth>().Health;
maxHP = GameObject.Find("Player").GetComponent<PlayerHealth>().maxHealth;
if (HP == maxHP)
{
isFull = true;
}
else { isFull = false; }
}
void OnTriggerEnter2D(Collider2D trig)
{
if ((trig.gameObject.tag == "Player") && (isFull == false))
{
Health = true;
Destroy(this.gameObject, 0.1f);
Debug.Log("I am health!");
}
}
}
If you need me to, I can post the entire player health script. Thanks in advanced!
Answer by sniper43 · Feb 24, 2015 at 11:17 AM
The line:
GameObject.Find("Heart").GetComponent<HealthPickup>().Health;
doesn't guarantee which heart will be found. If you have 2 hearts in your scene, it'll go awry most of the time.
Instead of searching for the heart from your player script, look for the player from the heart script.
Have your health pickup script increase desiredHealth by 30, then lerp desiredHealth and health like so:
health = Mathf.Lerp(health, desiredHealth, 0.5f);
This will give you your desired result reliably and make sure the health goes from one value to the other smoothly.
Also, look up the singleton pattern for making the health script.
Your answer
![](https://koobas.hobune.stream/wayback/20220613184142im_/https://answers.unity.com/themes/thub/images/avi.jpg)