Hey, I’ve been trying to make it so I have to click E in order to pick a weapon from the ground. I know that OnTrigger doesnt get called every frame so I tried creating a bool to make it work. However it didnt (other wise i wouldn’t be here) and to me, the code makes sense. I’m sure I’m missing out on something, can you help me?
Here’s the code:
Use The OnTriggerEnter / Exit. Additionally, you may pass over more than one weapon, or pass over a weapon immediately before a non-weapon.
In the latter case, your code would evaluate OnWeapTrig to false, despite you standing on a weapon.
You might have a few issues in the second statement, but without any extra explanations we can’t help too much there:
// Keep track of the weapons we're in range of
private List<Transform> nearbyWeapons = new List<Transform> ();
// This will be called whenever you enter a trigger collider
void OnTriggerEnter2D (Collider2D other)
{
// Check if this was a weapon
if ( other.CompareTag ("Weapon") )
{
// If so, add it to our list
this.nearbyWeapons.Add (other);
}
}
// This will be called whenever you enter a trigger collider
void OnTriggerExit2D (Collider2D other)
{
// Check if this was a weapon
if ( other.CompareTag ("Weapon") )
{
// Check if we had this previously, and if so remove it
if ( this.nearbyWeapons.Contains (other) )
{
this.nearbyWeapons.Remove (other);
}
}
}
// Your pickup function
public void OnWeaponPickup ()
{
// Make sure we were standing on something
if ( this.nearbyWeapons.Count == 0 )
return;
// You can choose what to do here for determining which weapon to use
Transform weapon = this.nearbyWeapons [0];
// Possible issue? If your weapon is full, it looks like you are
// trying to remove the current one, but then this statement will
// do nothing else following that?
//
if ( IsHolsterFull () )
{
DestroyWeaponInCurrentSlot ();
}
else
{
if ( currentWeapon != -1 )
{
DisableWeapon (currentWeapon);
}
currentWeapon++;
}
EquipWeaponInCurrentSlot (weapon);
}
I have several scripts that also use the E key to do stuff. i use onTriggerStay with Getkey because you only enter the trigger once and would need to be pressing the E key as you enter while you stay there and press E something happens.So the condition of being in trigger zone and pressing E is what this script does. The script goes on the triggerzone