Click here to Skip to main content
15,923,689 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, I am basically trying to keep the old text and while if you type in help it add a new line of text. the problem is the every time I type in help it prints the old text again (twice) and then prints the new text.
public Canvas myCanvas;
public Text myText;

private string display = "";

List<string> chatEvents;

private bool calltext;

public InputField inputfield;
private Dictionary<string, System.Action<string,string>> commands;

protected void Awake()
{
    commands = new Dictionary<string, System.Action<string,string>>();
    // Add the commands you want to recognise along with the functions to call
    commands.Add( "help", OnHelpTyped );
    // Listen when the inputfield is validated
    inputfield.onEndEdit.AddListener( OnEndEdit );
}

private void OnEndEdit( string input )
{
    // Only consider onEndEdit if the Submit button has been pressed
    if ( !Input.GetButtonDown( "Submit" ) )
        return;

    bool commandFound = false;

    // Find the command
    foreach ( var item in commands )
    {
        if ( item.Key.ToLower().StartsWith( input.ToLower() ) )
        {
            commandFound = true;
            item.Value( item.Key, input );
            break;
        }
    }

    // Do something if the command has not been found
    if ( !commandFound )
        Debug.Log( "No word found" );

    // Clear the input field (if you want)
    inputfield.text = "";
}

private void OnHelpTyped( string command, string input )
{
    chatEvents.Add ("The List");
    calltext = true;
}

// Use this for initialization
void Start () {
    chatEvents = new List<string>();

    chatEvents.Add("Welcome to my simple application ");
    chatEvents.Add ("Type help for list of commands");

    calltext = true;

}

// Update is called once per frame
void Update () {
    if(calltext)
    {
        AddText();
        calltext = false;
    }
}

void AddText()
{
    foreach(string msg in chatEvents)
    {
        display = display.ToString () + msg.ToString() + "\n";
    }
    myText.text = display;
}


What I have tried:

I have tried everything and it seems to work, but it adds the last two text plus the new text
Posted
Updated 11-Feb-17 20:34pm

1 solution

It happened because you did not clear the
display
before concatenating
msg.ToString()
, try this:
display = "";
foreach(string msg in chatEvents)
{
	display += msg.ToString() + "\n";
}
 
Share this answer
 
Comments
[no name] 13-Feb-17 0:31am    
Thanks for your reply and it works, thank you so much. I also have another question that is based on this question, but how would you go about and clear all the text on a command (say clear)?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900