I think is a common error make by users, but I don’t know what is wrong :
I make a GameManager with a default text prefab.
The script work well with focus on enter and add text when I press the space key.
After the chatBox.isFocused is focus all text is block and is not add to the text area : textObject.
The script is this :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameManager : MonoBehaviour {
public int maxMessages = 25;
public string username;
public GameObject chatPanel, textObject;
public InputField chatBox;
public Color playerMessage, info;
[SerializeField]
List<Message> messageList = new List<Message>();
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update()
{
if (!chatBox.isFocused)
{
if (Input.GetKeyDown(KeyCode.Space))
{
SendMessageToChat("You peressed the space key !", Message.MessageType.info);
Debug.Log("Space");
}
if (Input.GetKeyDown(KeyCode.Return))
{
chatBox.ActivateInputField();
}
}
else
{
if (Input.GetKeyDown(KeyCode.Return) && chatBox.text != "")
{
SendMessageToChat(username + "| " + chatBox.text, Message.MessageType.playerMessage);
chatBox.text = "";
}
}
}
public void SendMessageToChat(string text, Message.MessageType messageType)
{
if (messageList.Count >= maxMessages)
{
Destroy(messageList[0].textObject.gameObject);
messageList.Remove(messageList[0]);
}
Message newMessage = new Message();
newMessage.text = text;
GameObject newText = Instantiate(textObject, chatPanel.transform);
newMessage.textObject = newText.GetComponent<Text>();
newMessage.textObject.text = newMessage.text;
newMessage.textObject.color = MessageTypeColor(messageType);
messageList.Add(newMessage);
}
Color MessageTypeColor(Message.MessageType messageType) {
Color color = info;
switch (messageType) {
case Message.MessageType.playerMessage:
color = playerMessage;
break;
}
return color;
}
}
[System.Serializable]
public class Message
{
public string text;
public Text textObject;
public MessageType messsageType;
public enum MessageType
{
playerMessage,
info
}
}