- Home /
 
How to add symbols to string?
Hello guys. Trying to make a script, which after pressing a button adds a letter to the string. Each button = one letter. Made simple script, so that GET is the result string, which i need. But the problem is when i press the button, it doesn't add new symbol to string, but "refreshes" it, so that it shows just a one symbol ("A", for example - the name of the button), instead of showing "AA...".
 using UnityEngine;
 using System.Collections;
 using UnityEngine.UI;  
 
 public class Script : MonoBehaviour {
     public Button MyButton;
         
     
 
         void OnEnable()
         {
             
             MyButton.onClick.AddListener(MyFunction);
             
         }
         
 
         void MyFunction()
         {
         var GET = (this.gameObject.name);
             Debug.Log (GET);
         }
 
     }
 
               Would be very thankful for any help)
Answer by nullgobz · Aug 11, 2015 at 04:03 PM
This symbol = means assign, as in it will take whats on the right and stuff it to the left. This is why you get the same value.
You also need to use a member variable, rather then your local variable "GET". If you wish to "save" your value across diffrent method calls.
Here is an example of adding "this.gameObject.name" to a string rather then assigning.
  using UnityEngine;
  using System.Collections;
  using UnityEngine.UI;  
  
  public class Script : MonoBehaviour
 {
      public Button MyButton;
      private string theString;
  
      void OnEnable()
      {
         MyButton.onClick.AddListener(MyFunction);
      }
      void MyFunction()
      {
         theString += (this.gameObject.name);
         Debug.Log(theString);
      }
 }
 
              thanks, this works fine! But got another problem - it defines each button apartly, when i press "A" it writes AAAA, when press "B" - BBBB... Could you please tell, how can i "unite" them, so that there would be the one string for "ABAABBBABBABAB..." etc.... Thanks a lot!
make the member string static: private static string theString;
Answer by allenallenallen · Aug 11, 2015 at 03:58 PM
By typing this:
 var GET = (this.gameObject.name);
 
               You're overriding GET.
I recommend you to create a new variable to keep track of all the symbols.
 public var tracker = ""; // Declared in the beginning of the script.
 
               And to add more symbols, you do this:
 var GET = (this.gameObject.name);
 tracker += GET;
 
               Note: I haven't tested this so the syntax might or might not work.
Your answer