- Home /
Question by
recaigeciken14 · Aug 15, 2021 at 10:58 PM ·
inventoryitemsswapping
Swapping item in the inventory
Hey There! I have been making a UI inventory like click first item and second item to swap their position along slots. But the line in the commented below called problem starts - ends, items cliked are not swapped.Always the first clicked one change its properties as second one but the second always the same.
//Itemdata script includes eventSystems events like
//OnPointerClick to execute MoveItem method by
//clicking to the slot.
ItemData firstSlot, secondSlot;
public void MoveItem(GameObject clicked)
{
if (firstSlot== null)
{
//the -1 means if there is an item in the slot
if (clicked.GetComponent<ItemData>().item.id != -1)
{
Debug.Log("clicked first slot");
firstSlot = clicked.GetComponent<ItemData>();
firstSlot.GetComponent<Image>().color = Color.gray;
}
}
else if (secondSlot == null)
{
Debug.Log("clicked second slot");
secondSlot= clicked.GetComponent<ItemData>();
}
if (secondSlot != null && firstSlot != null)
{
Debug.Log("firstSlot AND secondSlot ARE NOT NULL ANYMORE");
//Problem lines starts
firstSlot.GetComponent<Image>().sprite = secondSlot.GetComponent<Image>().sprite;
secondSlot.GetComponent<Image>.sprite = firstSlot.GetComponent<Image>().sprite;
//Problem lines ends
secondSlot.GetComponent<ItemData>().item = firstSlot.GetComponent<ItemData>().item;
firstSlot.GetComponent<Image>().color = Color.white;
firstSlot= null;
secondSlot = null;
}
}
Comment
Answer by mak431020 · Aug 16, 2021 at 05:22 AM
First create a temporary variable to store first slot then store the second slot in the first slot and then store the temporary variable in the second slot var temp = first; first = second; second = temp;
This is not worked. I mean temp always changing its value. Even after assigning first=second.I cant hold the value inside the temp.