Home > Blockchain >  Unity For loop inside of OnTriggerEnter2D causes sometimes multiple outcomes
Unity For loop inside of OnTriggerEnter2D causes sometimes multiple outcomes

Time:12-21

Hi i am new to unity and programing in general so sorry if this is stupid question i am sure there are better ways to do this. Basicly i followed tutorial for inventory with draggable components and now i am implenting his methods to pick up items in my game. I tagged each item with his id. Tags are Item_0, Item_1, Item_2, etc.... and i am using for loop inside of OnTriggerEnter2D to determinate which item i picking up.

There is code for inventory:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Inventory : MonoBehaviour
{
    public List<Item> CharacterItmes = new List<Item>();
    public ItemDatabase itemDatabase;
    public UIInventory inventoryUI;
    [SerializeField] private GameObject inventory;

    private void Start()
    {
        inventoryUI.gameObject.SetActive(true);
     // Iniciate Items
        inventoryUI.gameObject.SetActive(false);
    }

    private void Update()
    {
        if (Input.GetButtonDown("Inventory"))
        {

            inventoryUI.gameObject.SetActive(!inventoryUI.gameObject.activeSelf);
        }
    }
    public void GiveItem(int id)
    {
        Item itemToAdd = itemDatabase.GetItem(id);
        CharacterItmes.Add(itemToAdd);
        inventoryUI.AddNewItem(itemToAdd);
       // Debug.Log("Added item: "   itemToAdd.title);
    }

    public void GiveItem(string itemName)
    {
        Item itemToAdd = itemDatabase.GetItem(itemName);
        CharacterItmes.Add(itemToAdd);
        inventoryUI.AddNewItem(itemToAdd);
       // Debug.Log("Added item: "   itemToAdd.title);
    }

    public Item CheckForItem(int id)
    {
        return CharacterItmes.Find(item => item.id == id);       
    }

    public void RemoveItem(int id)
    {
        Item itemToRemove = CheckForItem(id);
        if (itemToRemove != null)
        {
            CharacterItmes.Remove(itemToRemove);
            inventoryUI.RemoveItem(itemToRemove);
           // Debug.Log("Removed Item: "   itemToRemove.title);
        }
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        for (int i = 0; i <= 5; i  )
        {

            if (other.gameObject.CompareTag("Item_"   i.ToString()))
            {
                GiveItem(i);
                Debug.Log("Item_"   i.ToString());
                Destroy(other.gameObject);
            }
        }

        

    }
}

I have just 6 items for testing purposis right now latter i will replace lenght in for loop with variable with all items in ItemDatabase.

I have tagged all items with right tags and i was checking twice that my character has only 1 Collider2D and rigidbody so as all my items. Only 1 Collider2D set up as Trigger. So i have no clue why i sometimes pick up this items twice:

This is the result

Any ideas why it picking up multiple times or some better ways how to handle picking up itmes??? I will be glad for any advice. Thanks a lot

CodePudding user response:

Don't use a tag for every time you have, especially if it means you will have to loop through many items every time something is dragged over your inventory. It's unnecessary computation and could slow down your game if you have many kinds of items.

Instead, attach a simple mb to each item:

public class Pickupable : MonoBehaviour
{
    public int itemId;
}

Then in OnTriggerEnter2D, check if the trigger's attached to such a mb, and get the id from it if so:

Pickupable p = other.GetComponent<Pickupable>();
if (p != null)
{
    int id = p.itemId; 
    GiveItem(id);
    Debug.Log($"Item_{id}"); // format string is easier to read
    Destroy(other.gameObject);
}

CodePudding user response:

I am stupid. I indeed had multiple box colliders on my character. Only thing was that he was hidden in children GameObject and was providing functionality to other game mechanic so i deleted that BoxCollider and figured out that mechanic in other way. Now everything works clearly :)

So if anybody had similiar problem always make sure that you have Only 1 BoxCollider. On Object and Character as well

  • Related