Search Unity

Chat with keyboard ?

Discussion in 'Scripting' started by getzel, Dec 18, 2013.

  1. getzel

    getzel

    Joined:
    Nov 2, 2013
    Posts:
    27
    Hello i try to implement a chat in my multi-player game.
    We can't use the mouse because it's an fps.
    So i use the focus function on textfield when i press Return.
    But how to send the message instead of a "if (gui.button)" when i press Return in the textfield ?
    If i put a condition "if(Input.GetKey(KeyCode.Return))" it does nothing when its focused in the textfield...
    And how leave the focus of the textfield after that ?

    Thank you.
     
  2. Vapid-Linus

    Vapid-Linus

    Joined:
    Aug 6, 2013
    Posts:
    64
  3. getzel

    getzel

    Joined:
    Nov 2, 2013
    Posts:
    27
    Yes it's strange that a simple action like that, available on all games online, is hard to make in Unity (a chat with return key and not a click button).
    So, thank you, I almost succeeded. There is just one problem i cant solve :
    to press the SAME BUTTON Return to display the Textfield AND to send the message and make it disappear.
    I didn't manage well : the textfield didn't disappear and i couldn't send message if i remember.
    Because i think changing one boolean with the same input is hard.

    So i used Comma to display the textfield and Return to send the message.
    It writes a comma at the beginning of each message, annoying...

    But the script works so if it helps you or you can make it better, tell me :



    using UnityEngine;
    using System.Collections;
    using System.Collections.Generic;

    public class chat : MonoBehaviour {

    public string phrase = "";
    public List<string> phraseOut = new List<string>();


    public string namo;
    private bool entree = false;
    private bool send = false;


    void Start () {

    phraseOut.Add ("");
    phraseOut.Add ("");
    phraseOut.Add ("");

    }//start()


    void Update () {




    }//update()


    void OnGUI(){

    GUI.Label (new Rect (10,Screen.height-110,200,20), phraseOut[phraseOut.Count-3]);
    GUI.Label (new Rect (10,Screen.height-90,200,20), phraseOut[phraseOut.Count-2]);
    GUI.Label (new Rect (10,Screen.height-70,200,40), phraseOut[phraseOut.Count-1]);


    Event e = Event.current;

    if (e.keyCode == KeyCode.Return phrase!="") { entree = true; send = true; }


    if (e.keyCode == KeyCode.Comma) { entree = false; }

    if(entree == false) {

    // GUI.SetNextControlName("mytext");
    phrase = GUI.TextField(new Rect(10, Screen.height-50, 200, 20), phrase);

    }


    if (send)
    {

    send = false;
    networkView.RPC ("chatup",RPCMode.All,namo,phrase);
    phrase = "";

    }//if send




    }//gui


    [RPC]
    void chatup(string namo,string newPhrase)
    {
    phraseOut.Add(namo + " : " + newPhrase);

    }//chatup()

    }//class
     
    Last edited: Dec 19, 2013