Skip to content

Instantly share code, notes, and snippets.

@AldeRoberge
Created January 8, 2024 04:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AldeRoberge/c688e2f0c260da7be8b85f44accfa0f6 to your computer and use it in GitHub Desktop.
Save AldeRoberge/c688e2f0c260da7be8b85f44accfa0f6 to your computer and use it in GitHub Desktop.
ChatInputHistory using player prefs for Unity, not perfect but does the job
using System.Collections.Generic;
using UnityEngine;
namespace AGES.Networking.AGES.Networking.Runtime.Client.Scripts.UI.Chat
{
public class ChatInputHistory : MonoBehaviour
{
// Keeps a record of previous player chat input and allows the player to scroll through it
private readonly List<string> chatHistory = new();
private int historyIndex;
public void Start()
{
// Load from PlayerPrefs
if (PlayerPrefs.HasKey("ChatHistory"))
{
string[] history = PlayerPrefs.GetString("ChatHistory").Split('|');
foreach (string s in history)
{
if (string.IsNullOrEmpty(s))
continue;
// Do not add if already in the list
if (chatHistory.Contains(s))
continue;
chatHistory.Add(s);
}
}
}
public void Add(string input)
{
if (string.IsNullOrEmpty(input))
return;
if (chatHistory.Contains(input))
chatHistory.Remove(input);
chatHistory.Add(input);
historyIndex = chatHistory.Count;
// Save to PlayerPrefs
string history = "";
foreach (string s in chatHistory)
{
history += $"{s}|";
}
PlayerPrefs.SetString("ChatHistory", history);
}
public string Previous()
{
if (chatHistory.Count == 0)
return "";
historyIndex--;
if (historyIndex < 0)
{
historyIndex = chatHistory.Count - 1;
}
return chatHistory[historyIndex];
}
public string Next()
{
if (chatHistory.Count == 0)
return "";
historyIndex++;
if (historyIndex >= chatHistory.Count)
{
historyIndex = 0;
}
return chatHistory[historyIndex];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment