Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Referencing a canvas from a prefab

Discussion in '2D' started by ky0to_, Feb 28, 2021.

  1. ky0to_

    ky0to_

    Joined:
    Apr 12, 2020
    Posts:
    4
    Hi, I am quite new to Unity and I am currently working on a 2d dungeon crawler, similar to binding of isaac. I followed Blackthornprod's tutorial on making a health system
    ), but ran into trouble. I am using a prefab for my player , which means that I can't drag the heart images representing the player's health from my canvas (which is part of my hierarchy) into my 'hearts' array (located on my player prefab). Is there a way around this via script or Unity itself? I'll attach the code below! Thanks for your help.
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5.  
    6. public class PlayerHealth : MonoBehaviour
    7. {
    8.     public int health;
    9.     public int numOfHearts;
    10.  
    11.  
    12.  
    13.     public Image[] hearts;
    14.     public Sprite fullHeart;
    15.     public Sprite emptyHeart;
    16.  
    17.     private void Update()
    18.     {
    19.         if(health > numOfHearts)
    20.         {
    21.             health = numOfHearts;
    22.         }
    23.        
    24.         for (int i = 0; i < hearts.Length; i++)
    25.         {
    26.             if (i < health)
    27.             {
    28.                 hearts[i].sprite = fullHeart;
    29.             }
    30.             else
    31.             {
    32.                 hearts[i].sprite = emptyHeart;
    33.             }
    34.             if (i < numOfHearts)
    35.             {
    36.                 hearts[i].enabled = true;
    37.             }
    38.             else
    39.             {
    40.                 hearts[i].enabled = false;
    41.             }
    42.         }
    43.     }
    44.  
    45.  
    46.  
    47.  
    48.  
    49. }
     
  2. Derekloffin

    Derekloffin

    Joined:
    Mar 14, 2018
    Posts:
    322
    After you instantiate the player prefab, you should just have to set the hearts then. Whatever instantiates the player will be the place where you assign the hearts, and it would just pass along the values to the player prefab after instantiation. Alternately, you could just make the hearts part of your prefab. You can make UI prefabs just like anything else, so you can do it.