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)
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.
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);
}
}