I’m making a game where I have multiple shops. I was trying to us distance to check if I was in range, and then display a little text saying “Press E to talk” or something like that.
But when I tested it, i realized that you can only do that with one shop.
So is there another way to have multiple shops? if there is, could you explain in steps? ![]()
1 Answer
1using System.Collections.Generic;
using UnityEngine;
public class Shop : MonoBehaviour
{
static List<Shop> allShops = new List<Shop>();
void Awake()
{
allShops.Add(this);
}
public static Shop FindClosestShop(Vector3 targetPosition)
{
float closestDistance = float.MaxValue;
Shop closestShop = null;
foreach (Shop shop in allShops)
{
float distanceToTargetPosition = Vector3.Distance(shop.transform.position, targetPosition);
if (distanceToTargetPosition < closestDistance)
{
closestDistance = distanceToTargetPosition;
closestShop = shop;
}
}
if (closestShop != null)
{
Debug.Log("Found closest shop called " + closestShop.gameObject.name + ", at distance " + closestDistance);
}
return closestShop;
}
}
Sorry I didn't put this in the question, but I wan't when I'm in range I change a string to something I have predefined in unity itself. Like I have a string in the script, and I attach the script to the shopkeepers and I change the string there.
– Bokaii
Can you be more specific? What do you mean that you can only do that with one shop?
– WolfdogI mean, if I use the Using UnityEngine.UI; public Text display; public string displayText; void Update(){ float dist = Vector3.Distance(transform.position, player.position); if(dist<=3){ display.text = displayText; } else{ display.text = ""; } } And attach it to the shopkeeper, logically it doesn't work. But is there another way of doing this? ^^
– Bokaii