I've been having issues with a game I've been working on for a while. It's a pretty big project. I'm having some issues with two tree prefab game objects sharing code, where I don't want them to.
When the player presses E while facing them, they start searching the tree for items like apples. It was all working well, until I added another tree. Now, when I search one tree, it searches all trees in the scene. Obviously, I don't want that to happen.
I have provided my code, below. What am I doing wrong?
public class Search : MonoBehaviour
{
public List<Item> items;
public bool searched = false;
public GameObject inventory;
public Inventory inv;
public Log log;
public AudioSource takeSFX;
public GameObject player;
void Awake()
{
inventory = GameObject.Find(" Inventory Master");
inv = inventory.GetComponent<Inventory>();
}
void Start()
{
log = GameObject.Find(" Game Master").GetComponent<Log>();
AddItems();
items = new List<Item>();
}
void Update()
{
SearchObject();
}
public void AddItems()
{
int rand = (int)Random.Range(0, 2);
Debug.Log(rand);
for (int i = 0; i < rand; i++)
{
items.Add(inv.database.FetchItemByID(0));
}
}
public void SearchObject()
{
if (Input.GetButtonDown("Interact"))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit = new RaycastHit();
Debug.Log("Raycasting");
if (Physics.Raycast(ray, out hit, 10))
{
Debug.Log("Searching");
if (!searched)
{
this.takeSFX.Play();
if (items.Count >= -0)
{
for (int i = 0; i < items.Count; i++)
{
this.inv.AddItem(items[i].ID);
}
}
if (items.Count == 0)
log.UpdateLog("No items found in search.");
else if (items.Count == 1)
log.UpdateLog("1 item found in search.");
else
log.UpdateLog(items.Count + " items found in search.");
searched = true;
}
}
}
}
}
searchedvalue totrue. You probably want the player character to fire the ray (so it happens only once - raycasts have some cost) and then search/interact with the first thing that the ray hit. That way you can ensure you're only ever searching one thing at a time. \$\endgroup\$