As I see it you could achieve this in simplified ways using Dictionary
Option A
Rather use e.g. a Dictionary like
private Dictionary<string, int> indexByName = new Dictionary<string, int>()
{
{"basura", 0},
{"DinnerTime", 1},
{"atomo", 2},
{"extintor", 3},
}
private void OnTriggerEnter2D(Collider2D collision)
{
SetText(collision);
}
public void SetText(Collider2D other)
{
if(indexByName.TryGetValue(other.name, out var index)
{
cosita.text = msgEmergentes[index];
}
}
Option B
Why even take the route through an index? Simply directly use a dictionary like
private Dictionary<string, string> msgByName = new Dictionary<string, string>()
{
{"basura", "Whatever basura message"},
{"DinnerTime", "Hey, it's dinner time!"},
{"atomo", "Whatever other message"},
{"extintor", "Yet another message!"}
}
private void OnTriggerEnter2D(Collider2D collision)
{
SetText(collision);
}
public void SetText(Collider2D other)
{
if(msgByName.TryGetValue(other.name, out var msg)
{
cosita.text = msg;
}
}
Option C
Now if you still want to be able to adjust these in the Unity Inspector to be more flexible you could do something like
[Serializable]
public class KeyMessagePair
{
public string name;
public string message;
}
// Adjust these in the Inspector
public KeyMessagePair[] pairSetup;
private Dictionary<string, string> msgByName;
private void Awake ()
{
msgByName = new Dictionary<string, string>();
foreach(var pair in pairSetup)
{
msgByName.Add(pair.name, pair.message);
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
SetText(collision);
}
public void SetText(Collider2D other)
{
if(msgByName.TryGetValue(other.name, out var msg)
{
cosita.text = msg;
}
}
Of course you could/should also add some mechanics to avoid duplicate names but I think that should do it for now ;)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…