Search Unity

Modify GUI text via javascript

Discussion in 'Scripting' started by Teemo, Dec 22, 2014.

  1. Teemo

    Teemo

    Joined:
    Jun 20, 2013
    Posts:
    15
    I have this code:
    Code (csharp):
    1.  
    2. #pragma strict
    3. public var hpPoints : float = 3;
    4. public var CurrentHP : float = 3;
    5.  
    6.  
    7. function Start () {
    8. }
    9.  
    10. function Update () {
    11. var hits;
    12. var maxhits;
    13.  
    14. hits = GameObject.Find("hitstaken").guiText;
    15. maxhits = GameObject.Find("maxhits").guiText;
    16.  
    17. hits = CurrentHP.ToString;
    18. maxhits = hpPoints.ToString;
    19.  
    20. }
    21.  
    22. function OnCollisionEnter(collision: Collision) {
    23.  
    24.  
    25. if (collision.gameObject.tag == "obstacle"){
    26.    CurrentHP -= 1;
    27. }  
    28. print("You have hit an object. " + "You have " + CurrentHP + "/" + hpPoints + " HP points.");
    29.  
    30. if (CurrentHP <= 0){
    31.   print("You lost!");
    32.  }
    33. }
    34.  
    Everything works except the GUI part. They don't change how they are suposed to change.
    I tried to use "hits.text" but it told me that "text" is not a component of something.
    Ideeas ?
     
  2. Stardog

    Stardog

    Joined:
    Jun 28, 2010
    Posts:
    1,913
    You are making "hits" equal to a GuiText, but then you make it equal to a String on line 17. Strings don't have a "text" variable, only GuiText does.

    Change it to:

    Code (CSharp):
    1. hits.text = CurrentHP.ToString;
    2. maxhits.text = hpPoints.ToString;
    You should also move your "GameObject.Find"s to an Awake or Start function.