So I’m trying to have my player equip a weapon if he picks it up by instantiating the weapon object as a child of the player’s arms (this is a 2D game btw) and destroying the weapon he currently has equipped. The weapon object, however is not instantiating. Currently I’m referencing the weapon prefab through Resources.Load, but I’ve also tried dragging the prefab into the inspector just to check that I wasn’t somehow grabbing the wrong path name and that didn’t work either.
I know it’s trying to grab the correct object because my print statements are coming back correct. It just won’t show up in the hierarchy or scene. This script is on the weapon drop item that sits on the ground. When the player presses Q near it, one of the functions it runs is the EquipWeapon function.
Why isn’t it instantiating correctly?
void Start() {
weaponPrefab = Resources.Load("Prefabs/Items/PlayerWeapons/" + gameObject.name) as GameObject;
weaponID = weaponPrefab.GetComponent<Weapon>().weaponID;
playerArm = GameObject.Find("Arm");
}
public void EquipWeapon(int id)
{
Item weaponToAdd = itemDatabase.FetchItemByID(id);
print("Weapon to add: " + weaponToAdd.ItemName);
if (hotbarScript.currentlyEquippedWeapon != null)
{
Destroy(hotbarScript.currentlyEquippedWeapon);
GameObject weapon = Instantiate(weaponPrefab);
weapon.name = weaponToAdd.ItemName;
weapon.transform.SetParent(playerArm.transform);
hotbarScript.currentlyEquippedWeapon = weapon;
print("Currently equipped weapon: " + hotbarScript.currentlyEquippedWeapon.name);
}
}
private void OnTriggerStay2D(Collider2D collision)
{
if (collision.tag == "Player")
{
GetComponent<SpriteRenderer>().material = highlightMaterial;
if (Input.GetKeyDown(KeyCode.Q))
{
hotbarScript.AddItemToInventory(weaponID);
EquipWeapon(weaponID);
}
}
}