- Home /
My script for pick up items work is wrong! Help please
Script "Pick up", which is located on the ship. Inside the ship is a laser that destroys asteroids. According to the plan, the laser should destroy, and the ship, running into the drop-down resources - should pick them up. However, only a laser picks them up, who should not participate in this.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Podbor : MonoBehaviour
{
public AInv inventory;
private void OnTriggerEnter2D(Collider2D stolk)
{
if (stolk.gameObject.tag == "Res")
{
//Find existing item in inventory
for (int i = 0; i < inventory.items.Length; i++)
{
if (inventory.items[i].Name == stolk.GetComponent<AItem>().Name && inventory.items[i].stack != inventory.items[i].maxStack){
inventory.items[i].stack++;
Destroy( stolk.gameObject);
return;
}
}
//Find empty space for new item
for (int i = 0; i < inventory.items.Length; i++)
{
if (inventory.items[i].Name == "empty")
{
inventory.items[i].Name = stolk.GetComponent<AItem>().Name;
inventory.items[i].stack = stolk.GetComponent<AItem>().stack;
inventory.items[i].Image = stolk.GetComponent<AItem>().Image;
inventory.items[i].maxStack = stolk.GetComponent<AItem>().maxStack;
inventory.items[i].ID = stolk.GetComponent<AItem>().ID;
Destroy( stolk.gameObject);
break;
}
}
}
}
}
Answer by ashkanaral · Feb 23, 2020 at 12:06 AM
I think it is your if statement if (inventory.items[i].Name== "empty") maybe you have laser with "empty" probably you have "empty" ammo?
Also this might be the reason, you have
if (inventory.items[i].Name == stolk.GetComponent<AItem>().Name && inventory.items[i].stack != inventory.items[i].maxStack){
This has negation of stack and maxStack for existing item in inventory. Next, you have, find empty space for new item. You have stack and maxStack in for loop. You already have them negated and existing in your inventory. Now, you need to find empty space but you cannot because they will not allow ,maxStack. This may pick up with the laser. As an edit take out the maxStack on the second for loop or fix the if statement. Edit this:
if (inventory.items[i].Name == stolk.GetComponent<AItem>().Name && inventory.items[i].stack != inventory.items[i].maxStack){
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
chest items get added to inventory 2 Answers
Connecting Things to Weapon "Open Slot" 0 Answers
Multiple Cars not working 1 Answer
How would i check something in an Element in an array? 1 Answer