- Home /
[C#] Equip weapon from Inventory
I want to make a weapon-equip system and here is my try:
public Item currentWeapon;
public Item.ItemMunitionType munitionType;
public Transform playerHand;
public Transform equippedeItem;
public float reloadTime;
public float fireRate;
public float projectileSpeed;
public int range;
public int damage;
public int roundsPerBurst;
public bool canBurst;
public bool fullAuto;
if(Input.GetKeyDown("2"))
{
currentWeapon = inventoryScript.equippedPrimary;
equippedeItem = currentWeapon.itemTransform;
projectileSpeed = currentWeapon.itemProjectileSpeed;
range = currentWeapon.itemRange;
fireRate = currentWeapon.itemFireRate;
reloadTime = currentWeapon.itemReloadeTime;
damage = currentWeapon.itemDamage;
roundsPerBurst = currentWeapon.itemRoundsPerBurst;
canBurst = currentWeapon.itemCanBurst;
fullAuto = currentWeapon.itemFullAuto;
munitionType = currentWeapon.itemMunitionType;
equippedTransform (equippedeItem);
}
}
private void equippedTransform (Transform transform)
{
Transform selectedItem = Instantiate(transform, playerHand.position, Quaternion.identity) as Transform;
selectedItem.parent = playerHand;
selectedItem.localPosition = Vector3.zero;
selectedItem.localRotation = Quaternion.identity;
}
Of course the "If(Input.GetKeyDown("2"))" is in the update void. The problem is that the Transform won't show up.
Item is a class I wrote but it's not necessary to know for that.
For your Information: It compiles just fine and I assigned the transform manually.
I forgot to mention that I assigned the inventoryScript in the start void.
I'm not sure I understood what's the problem. Do you want your "Item" class to be exposed on the inspector? Or you want the Transforms to be exposed but they aren't?
I want the Transform of the object that I have currently equipped to show up in the scene(holstering a weapon for example)
http://answers.unity3d.com/questions/552598/equipting-a-sword.html
this guy had the same problem and did it like I did but for him it works. So where is the difference?
Answer by Joxno · Aug 21, 2014 at 12:47 PM
The reason is that you cannot instantiate a Transform, what you should be doing is instantiating a GameObject, which'll give you an empty gameobject with a transform that you can manipulate.
private void equippedTransform (Transform transform)
{
GameObject selectedItem = new GameObject("SelectedItem");
selectedItem.transform.position = playerHand.position;
selectedItem.transform.rotation = Quaternion.identity;
selectedItem.parent = playerHand;
selectedItem.localPosition = Vector3.zero;
selectedItem.localRotation = Quaternion.identity;
}