- Home /
Why does this prefab trigger all instances to action? C#
I've a turret prefab with script (below) attached and a large collision volume to act as trigger. The prefab is instantiated in 2 locations in the world. However, when enemy enters the trigger volume of 1 of the instances they both fire.
I've looked around for similar answers and tried lots to fix myself but for the life of me I can't see why this is doing this.
Any help MUCHLY appreciated :) - you guys have helped me so much already through me reading your fixes to others' problems.
public class GunController : MonoBehaviour
{
private float FireRate = 5.0f;
private float TimeBank = 0f;
private static int enemycount = 0;
void Start()
{
TimeBank = Time.time;
}
// Update is called once per frame
void Update()
{
if (enemycount > 0)
{
if ((Time.time >= FireRate + TimeBank))
{
SpawnBullet();
TimeBank = Time.time;
}
}
}
void SpawnBullet()
{
GameObject BasicProjectile = (GameObject)Resources.Load("BasicProjectile");
Instantiate(BasicProjectile, transform.position, transform.rotation); // spawn BasicProjectile
}
void OnTriggerEnter(Collider other)
{
enemycount ++;
Debug.Log(enemycount + " ENEMY IN");
}
void OnTriggerExit(Collider other)
{
enemycount --;
Debug.Log(enemycount + " ENEMY OUT");
}
}
Answer by syclamoth · Jun 12, 2012 at 04:36 PM
This happens because you are using a static variable to count the number of enemies that have entered the volume! This means that if one of them get triggered, all of them will count it, because the counter is shared between all of them!
You should just remove the 'static' keyword. It's not required, or even a good idea at the best of times.
What you are seeing here is why it's generally considered bad programming practice to use static variables in an object-oriented language. You should avoid them whenever you can.