- Home /
Focus chat input field when pressing enter
So i am looking for a way to make a chat input field that focuses when you press enter and sends the message when press enter another time. I have made a code that kind of works but not properly... Please help! using UnityEngine; using UnityEngine.UI; using System.Collections; using UnityEngine.EventSystems;
public class CEManager : MonoBehaviour {
public static InputField chatInput;
public GameObject networkManager;
private bool active = false;
private ChatManager chatManager;
private string username = "";
void Start ()
{
chatInput = GetComponent<InputField>();
chatManager = networkManager.GetComponent<ChatManager>();
}
void Update()
{
if(Input.GetKey(KeyCode.Return))
{
username = PlayerPrefs.GetString("currentUsername");
if(active == false)
{
chatInput.ActivateInputField();
EventSystem.current.SetSelectedGameObject(chatInput.gameObject, null);
active = true;
}
if(active = true)
{
if(chatInput.text == "")
{
}
else
{
chatManager.AddChatEvent(username + ":" + chatInput.text);
chatInput.text = "";
chatInput.DeactivateInputField();
active = false;
}
}
}
}
}
Comment
Best Answer
Answer by DM-Games · Dec 09, 2014 at 06:01 AM
I fixed it myself
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using UnityEngine.EventSystems;
public class CEManager : MonoBehaviour {
public static InputField chatInput;
public GameObject networkManager;
public GameObject chatEntry;
private bool active = false;
private ChatManager chatManager;
private string username = "";
public GameObject helpText;
void Start ()
{
chatInput = chatEntry.GetComponent<InputField>();
chatManager = networkManager.GetComponent<ChatManager>();
chatEntry.SetActive(false);
}
void Update()
{
if(Input.GetKeyUp(KeyCode.Return))
{
username = PlayerPrefs.GetString("currentUsername");
if(active == false)
{
chatEntry.SetActive(true);
EventSystem.current.SetSelectedGameObject(chatInput.gameObject, null);
chatInput.OnPointerClick(new PointerEventData(EventSystem.current));
active = true;
helpText.SetActive(false);
}
else
{
if(chatInput.text == "")
{
return;
}
else
{
chatManager.AddChatEvent(username + ":" + chatInput.text);
chatInput.text = "";
chatEntry.SetActive(false);
helpText.SetActive(true);
active = false;
}
}
}
if(active == true)
{
ChatManager.isChatOpen = true;
}
else if(active == false)
{
ChatManager.isChatOpen = false;
}
}
}
Answer by jenci1990 · Dec 07, 2014 at 02:42 PM
Change the update void like this:
void Update() {
if (Input.GetKeyDown(KeyCode.Return)) { //Change
username = PlayerPrefs.GetString("currentUsername");
if (active == false) {
chatInput.ActivateInputField();
EventSystem.current.SetSelectedGameObject(chatInput.gameObject, null);
active = true;
}
else { //Change
if (chatInput.text == "") {
}
else {
chatManager.AddChatEvent(username + ":" + chatInput.text);
chatInput.text = "";
chatInput.DeactivateInputField();
active = false;
}
}
}
}