So I’m trying to program a section where the player can interact with NPCs by walking next to them, the dialogue appearing, and after a certain distance disappearing. However, every way I approached this it always sets the text equal to the farthest NPC and not the closest. I don’t know what to do.
public class NPC : MonoBehaviour {
private Color col1;
private Color col2;
private Color col3;
private Color col4;
private Color col5;
public Transform trans;
public SpriteRenderer eye;
public string dialogue;
public controller pylr;
// Use this for initialization
void Start () {
pylr.npcs.Add(this);
int randNum = Random.Range(0, 4);
col1 = new Color(255, 0, 255, 255);
col2 = new Color(0, 255, 0, 255);
col3 = new Color(255, 0, 0, 255);
col4 = new Color(0, 0, 255, 255);
col5 = new Color(0, 255, 255, 255);
chooseColor(randNum, eye);
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.tag == "NPC")
{
int npcPlayerAt = 0;
float lowestDistance = 0f;
for (int i = 0; i < npcs.Count; i++)
{
float dist = Vector2.Distance(pl.position, npcs*.trans.position);*
if(dist<lowestDistance)
{
npcPlayerAt = i;
}
}
txt.text = npcs[npcPlayerAt].dialogue;
Debug.Log(npcPlayerAt);
}
else txt.text = “”;
}