I can’t see where you fill your ‘enemys’ array with enemies. Also, is your boxcollider set to ‘IsTrigger’ or it’s not?
However, to activate boxcollider on LMB click use this in ‘Update ()’:
using UnityStandardAssets.CrossPlatformInput;
public BoxCollider boxCollider;
void Update ()
{
// Switch collider 'On/Off' when left mouse buton is clicked
if (CrossPlatformInputManager.GetButtonDown ("Fire1")) {
boxCollider.enabled = !boxCollider.enabled;
}
To keep applying damage while RMB is hold down use this in either ‘Update ()’ or ‘OnCollisionEnter ()’ or ‘OnTriggerEnter ()’. Depends on how you determine collisions:
if (CrossPlatformInputManager.GetButton ("Fire2")) {
// Apply damage here
}
Point your attention to difference here. ‘GetButtonDown’ is true only once in a one single frame when button was pressed. ‘GetButton’ is true every frame while player holds the button pressed.
Now, let’s figure out what exactly you’re trying to do.
Do you want your boxcollider to actually collide with enemies so their rigidbodies would interact with it using physics engine? Or maybe you just want to use boxcollider to check if something is in it.
To make enemies collide with your boxcollider you need to make sure boxcollider’s property ‘IsTrigger’ is unchecked in inspector. If you do that, all enemies which have non-trigger colliders and rigidbodies will be pushed with your collider and ‘OnCollisionEnter ()’ will be called. Will they be pushed away or not depends on their (and yours) rigidbodies settings, such as ‘Mass’, ‘Drag’, position/rotation constraints.
To apply damage when enemies collide with your player non-trigger collider:
void OnCollisionEnter (Collision collision)
{
if (collision.gameObject.tag == "Enemy")
{
audioSource.Play();
HealthBar health = collision.gameObject.GetComponent<HealthBar>();
health.TakeDamage(damage);
}
}
If you check ‘IsTrigger’ on your boxcollider, then it will ignore all collisions and ‘OnCollisionEnter ()’ will never be called. For that case there’re another methods which are called when some colliders are going into your trigger-collider, these are:
‘OnTriggerEnter (Collider col)’ - called when some collider enters this collider. Returns ‘col’ which is triggered this event.
‘OnTriggerStay (Collider col)’ - called every time while collider ‘col’ is within your trigger-collider zone.
'OnTriggerExit (Collider col) - called when some collider is gone away from your trigger zone.
So, for example, to apply damage to all enemies in trigger-zone you could do:
using UnityStandardAssets.CrossPlatformInput;
void OnTriggerStay (Collider col)
{
// Check collider's tag and check if right mouse button is held down
if (col.tag == "Enemy" && CrossPlatformInputManager.GetButton ("Fire2")))
{
audioSource.Play();
HealthBar health = col.gameObject.GetComponent<HealthBar>();
health.TakeDamage(damage);
}
}