I am attempting to make a turret that will only track and shoot at the player if it is with in a certain radius. I found a good script on this site, but when I use it, unity will freeze up when my character enters the trigger area.
The code I am using is this:
private var target : Transform;
var damping = 6.0;
var smooth = true;
var bulletPrefab : Rigidbody;
var bulletSpeed : float = 100;
function OnTriggerEnter(otherCollider : Collider) {
if (otherCollider.CompareTag("player"))
{
target = otherCollider.transform;
Fire();
}
}
function OnTriggerExit(otherCollider : Collider) {
if (otherCollider.CompareTag("player"))
{
target = null;
StopCoroutine("Fire"); // aborts the currently running Fire() coroutine
}
}
function Fire()
{
while (target != null)
{
var nextFire = Time.time + 1;
while (Time.time < nextFire)
{
if (smooth)
{
// Look at and dampen the rotation
var rotation = Quaternion.LookRotation(target.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping);
}
else
{
// Just lookat
transform.LookAt(target);
}
}
// fire!
var bullet = Instantiate(bulletPrefab, transform.position, transform.rotation);
bullet.velocity = transform.forward * bulletSpeed;
}
}
I have my fireball prefab linked to the bulletPrefab, my character is tagged “player”, and I am using a spherical collider for the trigger. Any ideas why my game would crash?