Hi, I have used the script, which I called healthEffects, and applied it to two different objects (a sphere and a cylinder...

Hi, I have used the script, which I called healthEffects, and applied it to two different objects (a sphere and a cylinder). My idea is to have some collisions that give points, and some that take them away. I have given a negative pick up amount to the sphere, and a positive to the cylinder. They both have isTrigger ticked, and they both have colliders. The sphere works, but the cylinder does not. I have tried putting the cylinder above the sphere in the hierarchy, but that doesn't change anything. The player is tagged with 'player'. Any ideas? using UnityEngine; using UnityEngine.UI; using System.Collections; public class healthEffects : MonoBehaviour { public Text healthText; public int pickupAmount = 10; public int currentHealth = 50; // Use this for initialization void Start () { healthText = GameObject.Find ("Text").GetComponent (); } // Update is called once per frame void Update () { healthText.text = "Health " + currentHealth; } void OnTriggerEnter (Collider col) { if (col.gameObject.tag == "Player") { currentHealth += pickupAmount; } } }
  • Nicholas Yang(nyanginator) replied

    If you've applied the script on 2 separate objects, then they are keeping track of 2 separate health amounts, and the sphere seems to be winning out in the text display. You want both scripts to reference the same health value. One way to do this is to create an Empty game object "Health" with this script "HealthScript" to hold that health value:

    using System.Collections;
    using UnityEngine;
    
    public class HealthScript : MonoBehaviour {
        public int currentHealth = 50;
    }

    And then adjust the pickup script:

    using System.Collections;
    using UnityEngine;
    using UnityEngine.UI;
    
    public class PickupHealth : MonoBehaviour {
        public Text healthText;
        public int pickupAmount = 10;
    
        // Reference to HealthScript component in the Empty
        public HealthScript health;
    
        void Start() {
            healthText = GameObject.Find("Text").GetComponent();
    
            // Assuming that the Empty is named "Health"
            health = GameObject.Find("Health").GetComponent();
        }
    
        void Update() {
            // Grab the health value from the HealthScript
            healthText.text = "Health: " + health.currentHealth;
        }
    
        void OnTriggerEnter(Collider col) {
            if (col.gameObject.tag == "Player") {
                // Update the health value in the HealthScript
                health.currentHealth += pickupAmount;
            }
        }
    }