P
P
privet_andrei1232020-04-14 16:02:06
C++ / C#
privet_andrei123, 2020-04-14 16:02:06

Why does the code work 1 time?

In general, when you press the space button, the script looks for objects with a tag that are not far away and if it is no more than 2m away. then it looks for an object whose id is equal to = or the object id . transfers this object to the inventory deleting it and stops the loop . how is it in the game he raises the object and does not delete other objects !! please tell me how to fix this?

void AddItem()
    {
        if(Input.GetKeyDown(KeyCode.Space))
        {
            for(int i = 0; i < items.Length;i++)
            {
                if (Vector3.Distance(transform.position, items[i].transform.position)< 2)
                {
                    
                    for (int e = 0; e < Inventory.transform.childCount; e++)
                    {

                        slot = Inventory.transform.GetChild(e);
                        if (slot.GetComponent<SlotIfo>().id == 0 || slot.GetComponent<SlotIfo>().id == items[i].GetComponent<Item>().id)
                        {                                              
                            slot.GetComponent<SlotIfo>().id = items[i].GetComponent<Item>().id;
                            slot.GetComponent<SlotIfo>().icon = items[i].GetComponent<Item>().icons;
                            slot.GetComponent<SlotIfo>().count = slot.GetComponent<SlotIfo>().count + items[i].GetComponent<Item>().count;
                            Destroy(items[i]);
                            break;
                        }
                       
                    }
                  
                }
                else
                {
                    Debug.Log(i);
                }
            }
        }
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
privet_andrei123, 2020-04-14
@privet_andrei123

I fixed it by adding at the beginning of the method items = GameObject.FindGameObjectsWithTag("item");

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question