I am working on some functionality to handle item pickups for a player.
I have a GameObject variable called ‘pickupEquipped’ which is set whenever a player picks up an item (using raycasting and the mouse button). It sets it to the prefab they clicked on. When they click on another item, it destroys the item they clicked on, and instantiates their previously equipped item at the transform of the item they just picked up (swapping them out).
The problem is, once they click on the item, it destroys the gameobject they clicked on (so nobody else can pick it up, and it doesn’t show up anymore). When I do this, the pickupEquipped variable becomes (Missing) in the inspector, so when I try to pick up another item, and ‘instantiate’ it I get an error that the prefab is missing. How do I grab the ‘root’ prefab item from the ‘Resources’ folder so that it uses that, instead of the actual in-scene clone that it captured?
I have included my code that handles the clicking of the item, and the PickupItem function on the CharacterController script.
In my player camera script for handling raycasting and picking up the item
_selection is set to the transform of the object the raycast hit.
the _selection.transform.gameObject.name).GetComponentInChildren().itemPrefab; is a reference to the ‘actual’ prefab in the resources folder.
if (Input.GetMouseButtonDown(0) && _selection != null)
{
GameObject itemPrefab = GameObject.Find(_selection.transform.gameObject.name).GetComponentInChildren<ItemController>().itemPrefab;
// Prefix (Item prefab of item you picked up, current hovered item);
GameObject.Find("Player").GetComponent<CharacterController>().PickupItem(itemPrefab,_selection.transform.gameObject);
_selection = null;
}
and in CharacterController.cs
public void PickupItem(GameObject itemPrefab, GameObject _selection)
{
// This code successfully destroys the old object, and instantiates a new one based on the item you are holding as well as updates the icon
GameObject tempItem = _selection;
// If you already have an item picked up, drop it down (Something seems to be happening here, not sure what
if (pickupEquipped != null)
{
Debug.Log(pickupEquipped);
Instantiate(pickupItem, new Vector3(tempItem.transform.position.x, tempItem.transform.position.y, tempItem.transform.position.z), tempItem.transform.rotation);
tempItem = null;
}
pickupEquipped = itemPrefab;
Sprite icon = itemPrefab.GetComponent<ItemController>().itemIcon;
// Set the sprite of inventory slot 1 to the item you picked up
GameObject.Find("Player/GameUI/pickupItem").SetActive(true);
GameObject.Find("Player/GameUI/pickupItem").GetComponent<Image>().sprite = icon;
Destroy(_selection);
}
I know WHY what is happening is happening (because I am storing the ‘cloned’ prefab (which is being deleted so the reference goes away) into the variable, instead of the actual ‘prefab’ in the ‘Resources’ folder. I am trying to find out how I can get that object using the cloned prefab as a reference.