I am figuring out a mining script so that player can mine rocks and what not. It somewhat works but not as I would like it to. Basically it works for the first rock but any other rocks i place are not working at all. For example if i place just 1 rock it works fine. If i add 3 more rocks only the 4th one works and the first three don’t.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MiningRocks : MonoBehaviour
{
public int distancetomine = 2;
bool rockInRange;
GameObject rock;
IronOre ironore;
// Use this for initialization
void Awake()
{
rock = GameObject.FindGameObjectWithTag("IronOre");
ironore = rock.GetComponent<IronOre>();
}
// Update is called once per frame
void Update()
{
float distance = Vector3.Distance(this.transform.position, GameObject.FindGameObjectWithTag("IronOre").transform.position);
if (Input.GetKeyDown(KeyCode.E) && distance <= distancetomine && rockInRange == true)
{
ironore.IronOreHealth -= 1;
}
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject == rock)
{
rockInRange = true;
}
}
void OnTriggerExit(Collider other)
{
if (other.gameObject == rock)
{
rockInRange = false;
}
}
void OnGUI()
{
float distance = Vector3.Distance(this.transform.position, GameObject.FindGameObjectWithTag("IronOre").transform.position); ;
if (distance <= 2)
{
GUI.Box(new Rect(400, 200, 220, 22), "Press E to gather");
}
}
}
Script is attached to the player. I would appreciate any help on what i am doing wrong.
PS (if i place 3 rocks) the GUI only shows for the 3rd rock placed. If i mine that rock it then shows to for 2nd and then for the first while it should show for all at all times + if i try to mine 1st or 2nd rock it doesnt work. It only works if i go 3rd>2nd>1st.