- Home /
Question by
brockmcn · Jul 11, 2017 at 08:04 PM ·
tagsinteraction
Interacting with gameobjects of same tag
private Transform indicator;
private GameObject[] chest;
private LootScript lootScript;
public int money;
void Start () {
indicator = gameObject.transform.GetChild(0);
chest = GameObject.FindGameObjectsWithTag("Chest");
lootScript = chest[0].GetComponent<LootScript>();
}
void Update () {
if (Input.GetButtonDown("Interact"))
{
foreach (GameObject chests in chest)
{
if (Vector2.Distance(indicator.transform.position, chests.transform.position) == 0)
ChestInteract();
}
}
void ChestInteract()
{
money += lootScript.money;
lootScript.money = 0;
}
The same chest is affected every time. The first chest never loses its money, if the player interacts with the first chest, the second chest loses money and if the player interacts with the second chest, the second chest still loses the money.
Comment
Answer by Jwizard93 · Jul 11, 2017 at 08:45 PM
private Transform indicator;
private GameObject[] chest;
private LootScript lootScript;
public int money;
void Start () {
indicator = gameObject.transform.GetChild(0);
chest = GameObject.FindGameObjectsWithTag("Chest");
}
void Update () {
if (Input.GetButtonDown("Interact"))
{
foreach (GameObject chests in chest)
{
if (Vector2.Distance(indicator.transform.position, chests.transform.position) == 0)
lootScript = chests.GetComponent<LootSCript>();
ChestInteract();
}
}
void ChestInteract()
{
money += lootScript.money;
lootScript.money = 0;
}
You had the lootscript always reffering to the first chest found by GameObject.Find....
Also consider renaming variables you are using plurality in the exact opposite way than regular English.