Search Unity

Question UI GetComponent

Discussion in 'Scripting' started by BetrayedPickle, Jun 8, 2020.

  1. BetrayedPickle

    BetrayedPickle

    Joined:
    Mar 30, 2019
    Posts:
    119
    I am trying to make a script so when you pick up an object, a checkmark shows up. The way I want to do this is by disabling the Image component on the Checkmark UI, and when IngredientCollected is true, have the checkmark show up by activation the Image component again. How could I do this? This is what I have so far.
    Also, I don't know if this will help you understand the code better or not but the public PickUp1 pickup1 is me accessing the variable IngredientCollected from that script and using it in this CollectCheck script.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UIElements;
    5.  
    6. public class CollectCheck : MonoBehaviour
    7. {
    8.  
    9.     public PickUp1 pickup1;
    10.     public Image checkmark;
    11.  
    12.    
    13.     void Start()
    14.     {
    15.         checkmark = GetComponent<Image>();
    16.         checkmark.visible = false;
    17.     }
    18.  
    19.     void Update()
    20.     {
    21.         if (pickup1.IngredientCollected == true)
    22.         {
    23.             checkmark.visible = true;
    24.         }
    25.     }
    26. }
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,742
    Line 15 is not necessary if you are using line 10 to drag the Image in from the inspector. It's either-or: you either need to find it at runtime like you're doing, but this code won't find it if it is saved disabled, which is why traditionally a reference is dragged into line 10. If you drag a reference into line 10, and it is disabled, executing line 15 will set that reference back to null. Do only one or the other.

    If you absolutely must find it at runtime, make sure you use the variant of .GetComponent that will return disabled components. See docs.