Reply To: Instantiating Prefab Problems

Forum Archive Instantiating Prefab Problems Reply To: Instantiating Prefab Problems

#34519
Jonathan Gonzalez
Participant

    The script itself seems to be working fine. I created a prefab of a cube that uses the script and adjusted the health amount for each and they worked separately just fine with their own unique health amounts. I did make some slight modifications to your script to make it a bit cleaner and more efficient:

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class Health : MonoBehaviour
    {
        public float size = 1, health = 50000;
    
        void Update()
        {
    
            //Health loses one every time Update is cycled through
            health -= size;
    
            //If they run out of health they die
            if (health < 0)
            {
                Destroy(gameObject);
            }
    
        }
    
    
        void OnTriggerEnter(Collider col)
        {
            if(col.CompareTag("Food")){
                //If they find a piece of food they gain 2500 health
                health += 2500;
                Destroy (col.gameObject);
            }
        }
    }

    For the changes I removed the game object. If this is applied directly to the baby, and you want to destroy it, use gameObject to reference “this” game object. The OnTriggerEnter is set to private by default, same with any other method like Update. I removed the switch statement since it was just one check, using an if statement would be a bit easier. When referencing a tag of a game object that entered you can use “col.CompareTag”. For the health I added the value instead of using health + 2500. Lastly I also destroyed the object that entered the trigger zone after adding the health. 

    I would recommend creating a new prefab and using that when you instantiate. It’s possibly an organization issue. Test it with a few prefabs and a known good parent to drill down to the issue.