'How to collect the crafted item into inventory in unity2d
Currently, I want to make a mini game where the player can craft item from very fundamental item to very advanced item (e.g. from a piece of wood then craft it into a spear). Basically it is some sort of Crafty by Brackeys but I would like to make my own version of Crafty!
I have been following the tutorial: https://www.youtube.com/watch?v=1fbd-yTcMgY&t=336s The crafting system is very simple to understand. I also finished a inventory system that can store the material but now I am facing a problem is that I cannot collect the crafted item from the Result Slot. Does anyone know code the coding in the video so that I able to collect the item from Result Slot into my inventory?
Code is posted as below. Thank you in advances
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class CraftingManager : MonoBehaviour
{
private Item currentItem;
public Image customCursor;
public Slot[] craftingSlots;
public List<Item> itemList;
public string[] recipes;
public Item[] recipeResults;
public Slot resultSlot;
private void Update()
{
if (Input.GetMouseButtonUp(0))
{
if(currentItem != null)
{
customCursor.gameObject.SetActive(false);
Slot nearestSlot = null;
float shortestDistance = float.MaxValue;
foreach(Slot slot in craftingSlots)
{
float dist = Vector2.Distance(Input.mousePosition, slot.transform.position);
if (dist < shortestDistance)
{
shortestDistance = dist;
nearestSlot = slot;
}
}
nearestSlot.gameObject.SetActive(true);
nearestSlot.GetComponent<Image>().sprite = currentItem.GetComponent<Image>().sprite;
nearestSlot.item = currentItem;
itemList[nearestSlot.index] = currentItem;
currentItem = null;
CheckForCreatedRecipes();
}
}
}
public void OnClickSlot(Slot slot)
{
slot.item = null;
itemList[slot.index] = null;
slot.gameObject.SetActive(false);
CheckForCreatedRecipes();
}
public void OuMouseDownItem(Item item)
{
if (currentItem == null)
{
currentItem = item;
customCursor.gameObject.SetActive(true);
customCursor.sprite = currentItem.GetComponent<Image>().sprite;
}
}
void CheckForCreatedRecipes()
{
resultSlot.gameObject.SetActive(false);
resultSlot.item = null;
string currentRecipeString = "";
foreach(Item item in itemList){
if(item != null)
{
currentRecipeString += item.itemName;
}
else
{
currentRecipeString += "null";
}
}
for (int i = 0; i < recipes.Length; i++)
{
if(recipes[i] == currentRecipeString)
{
resultSlot.gameObject.SetActive(true);
resultSlot.GetComponent<Image>().sprite = recipeResults[i].GetComponent<Image>().sprite;
resultSlot.item = recipeResults[i];
}
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
