Skip to content

Instantly share code, notes, and snippets.

@farukcan
Last active October 8, 2022 12:32
Show Gist options
  • Save farukcan/90602e53bc11813cc0522597f6f25efa to your computer and use it in GitHub Desktop.
Save farukcan/90602e53bc11813cc0522597f6f25efa to your computer and use it in GitHub Desktop.
Unity Easy Set Texts Remotely
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
[RequireComponent(typeof(Text))]
public class RemoteText : MonoBehaviour
{
private static Dictionary<string,List<RemoteText>> Instances = new Dictionary<string,List<RemoteText>>();
private static Dictionary<string,Action<string>> Listeners = new Dictionary<string,Action<string>>();
public string key = "Level";
private Text text;
public Text Text => text==null ? text = GetComponent<Text>() : text;
public void SetText(string t) => Text.text = t;
private static void SetAll(string key, string t) => Instances[key].ForEach(x=>x.SetText(t));
private void Awake(){
if(!Instances.ContainsKey(key)){
Instances.Add(key,new List<RemoteText>());
}
Instances[key].Add(this);
}
private void OnDestroy() => Instances[key].Remove(this);
void Reset() => key = gameObject.name;
public static Setter Set = new Setter();
public class Setter
{
public string this[string key]
{
get => Instances[key].First().Text.text;
set {
if(Listeners.ContainsKey(key)){
Listeners[key]?.Invoke(value);
}
SetAll(key,value);
}
}
}
public static Listener Listen = new Listener();
public class Listener
{
public Action<string> this[string key]
{
get => Listeners.ContainsKey(key) ? Listeners[key] : Listeners[key] = (s)=>{};
set => Listeners[key] = value;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment