Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Update an Instantiated UI Text

Discussion in 'Immediate Mode GUI (IMGUI)' started by Meckes, Jun 20, 2017.

  1. Meckes

    Meckes

    Joined:
    Jun 20, 2017
    Posts:
    4
    Hello everyone,

    i have a little Problem with updating my Instantiated UI Text.

    Code (CSharp):
    1.     using UnityEngine.UI;,
    2.    
    3.     public Canvas UI;
    4.     public Text AmmoCurrentText;
    5.     public Text AmmoMaxText;
    6.     public float ammo;
    7.    
    8.         void Awake(){
    9.         Instantiate (UI);
    10.     }
    11.    
    12.         void Start() {
    13.         AmmoCurrentText.text = ammo.ToString ();
    14.         AmmomaxText.text = ammo.ToString ();
    15.     }
    16.        
    17.         void shoot (){
    18.             ammo--;
    19.         AmmoCurrentText.text = ammo.ToString ();
    20.         }
    Starting the first Time, the Current and the Max Text is empty. After the second Start the Current and the Max Text using the ammo float, but while playing and using the shoot method, the Text is not updating.

    Can someone help me?
     
  2. LaneFox

    LaneFox

    Joined:
    Jun 29, 2011
    Posts:
    7,462
    Instantiate will create a copy of the given object in the scene. You aren't referencing this new Canvas (UI) anywhere, so I assume you're not pointing at the correct Text components. You're probably targeting some prefab components instead of the instanced runtime ones.
     
    Meckes likes this.
  3. Meckes

    Meckes

    Joined:
    Jun 20, 2017
    Posts:
    4
    Thanks for reply!

    Now i tried it with non Instantiated UI Text and the Start Problem is solved but, its still not updating while shooting.
     
  4. LaneFox

    LaneFox

    Joined:
    Jun 29, 2011
    Posts:
    7,462
    Are you ever invoking the 'shoot()' method on this class? Add a Debug.Log("message") to check it is being invoked.
     
  5. Meckes

    Meckes

    Joined:
    Jun 20, 2017
    Posts:
    4
    I already tried to Debug.Log the method, it's working... This is the reason why i'm wondering ...
     
  6. LaneFox

    LaneFox

    Joined:
    Jun 29, 2011
    Posts:
    7,462
    Is AmmoCurrentText pointing to the correct component?
     
  7. Meckes

    Meckes

    Joined:
    Jun 20, 2017
    Posts:
    4
    i think so. or how else could it work at the start?
    now i also Debug.Log the Ammo and the Console shows the right value.
     

    Attached Files: