Script is causing immense lag, and I don't know what's causing it.

I have zombies in a game that fire mini projectiles at players, and have health scripts as well. I know it’s one of their scripts because adding them to the game causes it to quickly become laggy, and then unplayable.

this is the HP script,

var HP : int = 5;
var body : GameObject;
var speed : int = 5;


function Start () {
body = gameObject;
}

function Update () {

transform.Translate(Vector3(0,0,speed) * Time.deltaTime);

	if(HP < 1) {
		var instance : GameObject = Instantiate(body, transform.position, transform.rotation);
		DestroyObject (gameObject);
	}
}

function OnCollisionEnter (myCollision : Collision) {
	
	if(myCollision.gameObject.name == "zombieclimb"){
		
		transform.Translate(Vector3(0,1,0) * Time.deltaTime);
		
	}
}

and the shooting script,

var projectile : GameObject;

var startdelay = 0.1;
var delay = 0.1;

InvokeRepeating("LaunchProjectile", startdelay, delay);


function LaunchProjectile () {
	
	var instance : GameObject = Instantiate(projectile, transform.position, transform.rotation);
		
}
	
	
	
function Start () {
projectile = gameObject;
}

Again, I don’t know what is causing it, but I suspect it may be the Update function. Also, nothing appears in the console either.

Hi,

If you start lagging after you shoot for a while, then add this piece of code to your ‘LaunchProjectile’ funtion: Destroy(instance, 10)

That will destroy the instantiated bullet after 10 seconds.

Other than that, everything looks fine to me and I cannot locate anything else that might lag your game right now.

Please ask if you need further assistance.

Best of luck,

SeeSharp.

The InvokeRepeating() shouldn’t even work, as it is outside a function. You can declare variables outside a function but not do anything else.

If it did work, it looks like the object with this “shooting script” on it would copy itself 10 times a second, and all of those copies would make copies of themselves 10 times a second, exponentially overflowing your scene with instances and probably crashing the game.