Problems With Health pack Script

I’m placing this code

using UnityEngine;
using System.Collections;
public class HealthTrigger : MonoBehaviour {
    // Use this for initialization
    void Start () {
    }
    // Update is called once per frame
    void Update () {
    }
    void OnTriggerEnter(Collider other)
    {
        GameObject Player = GameObject.Find("Player");
        PlayerHealth playerhealth = Player.GetComponent<PlayerHealth>();
        playerhealth.curHealth += 10;
        Destroy (gameObject);
        audio.Play();
    }
}

on a heart container in my adventure game, it gets the value of curHealth and is supposed to add ten health disapeer and play a sound, any Help?
P.S. Yes Heart container is a trigger

Hi!

First I’ll repost your code with breaks so it’s easier to read :smiley:

using UnityEngine;
using System.Collections; 
public class HealthTrigger : MonoBehaviour { 
  //Use this for initilization 
  void Start () { } // Update is called once per frame
  void Update () { }

  void OnTriggerEnter(Collider other) { 
    GameObject Player = GameObject.Find("Player");
    PlayerHealth playerhealth = Player.GetComponent(); 
    playerhealth.curHealth += 10; 
    Destroy (gameObject); 
    audio.Play();
  }
}

Ok, first off, the reason your audio isn’t playing is because you destroy the gameObject before you try to play it. A good solution to this is:

playerhealth.curHealth += 10;
renderer.enabled = false; //Objects mesh isn't visible 
audio.Play();
yield WaitForSeconds (audio.clip.length); //Waits until audio is finished
Destroy (gameObject);

Now for the problem with the health not being added.

I think the reason for this could be that you are working with a local instance of the component. Try writing a method in PlayerHealth like:

void AddHealth(int health){
  curHealth += health;
}

and see if that works.

Are you sure you’re getting the correct component? I’m not used to C# so I haven’t seen GetComponent used like that without anything in the () before :slight_smile:

Good Luck! I hoped I was to some help!

Robin