Advertisement
StanHebben

Moving and counting inventory items

Nov 16th, 2016
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.33 KB | None | 0 0
  1.  
  2. // Attempts to fill given target to the given amount of the given item by transferring it
  3. // from the list of sources
  4. private void LoadItem(
  5. List<IMyTerminalBlock> sources,
  6. IMyTerminalBlock target,
  7. string id,
  8. string subid,
  9. VRage.MyFixedPoint amount)
  10. {
  11. if (target == null)
  12. return;
  13.  
  14. var todo = amount - CountItems(target, id, subid);
  15. if (todo <= 0)
  16. return;
  17.  
  18. var targetInventory = target.GetInventory(0);
  19. foreach (IMyTerminalBlock source in sources)
  20. {
  21. for (int i = 0; i < source.GetInventoryCount(); i++)
  22. {
  23. var inventory = source.GetInventory(i);
  24. var items = inventory.GetItems();
  25. for (int j = 0; j < items.Count; j++)
  26. {
  27. var item = items[j];
  28.  
  29. if (!item.Content.TypeId.ToString().Equals(id))
  30. continue;
  31.  
  32. if (!item.Content.SubtypeName.Equals(subid))
  33. continue;
  34.  
  35. var transfer = VRage.MyFixedPoint.Min(todo, item.Amount);
  36. if (!inventory.IsConnectedTo(targetInventory))
  37. continue;
  38.  
  39. inventory.TransferItemTo(targetInventory, j, null, true, transfer);
  40. todo -= transfer;
  41. if (todo <= 0)
  42. return;
  43. }
  44. }
  45. }
  46. }
  47.  
  48. // Counts the number of items of a given type in the given block
  49. private VRage.MyFixedPoint CountItems(IMyTerminalBlock block, string id, string subid)
  50. {
  51. if (block == null)
  52. return 0;
  53.  
  54. VRage.MyFixedPoint result = 0;
  55. for (int i = 0; i < block.GetInventoryCount(); i++)
  56. {
  57. var inventory = block.GetInventory(i);
  58. foreach (var item in inventory.GetItems())
  59. if (item.Content.TypeId.ToString() == id && item.Content.SubtypeName == subid)
  60. result += item.Amount;
  61. }
  62. return result;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement