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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

[Solved] ().Text += 30 problem - PLEASE HELP TO BEGINNER

Discussion in 'Scripting' started by latasever8, Apr 29, 2020.

  1. latasever8

    latasever8

    Joined:
    Jun 22, 2019
    Posts:
    16
    Hi brothers. In game, for example I have 70 health, I took +30 medicine and it should be 100 but it looks like "7030"
    please help me what should I do?

    Code (CSharp):
    1. canis.GetComponent<Text> ().text += 30;
    here is my code
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,735
    When you add a string and an integer in C#, the compiler converts the integer to a string and then concatenates them. So 30 gets converted to the string "30", then "70" + "30" gives "7030", just like "Monkey" + "Wrench" gives you "MonkeyWrench". You could quickly fix your script like this:

    Code (CSharp):
    1. Text text = canis.GetComponent<Text>();
    2. // Parse the string value as an integer
    3. int currentHealth = Int32.Parse(text.text);
    4. // Add 30
    5. var newHealth = currentHealth + 30;
    6. // Put the string version of the new health value back into the text component
    7. text.text = newHealth.ToString();
    However a more robust solution would be to store your health in an actual int value somewhere, and update the text when that value changes using either a property setter or an event.
     
    matkoniecz and latasever8 like this.
  3. latasever8

    latasever8

    Joined:
    Jun 22, 2019
    Posts:
    16
    actually I see an int32.parse code first time so I couldnt edit it for myself. and I get a problem
    The name `Int32' does not exist in the current context
     
  4. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,735
    "int" is a type alias for Int32, so you can also just use:
    Code (CSharp):
    1. int.Parse()
    Alternatively, put this at the beginning of your file:
    Code (CSharp):
    1. using System;
    then you can use "Int32"
     
    latasever8 likes this.
  5. latasever8

    latasever8

    Joined:
    Jun 22, 2019
    Posts:
    16
    you're incredible!!!!!!!!!
    thanks so much