(2D/UnityScript) Instantiating A Prefab Then Destroying It Every Few Seconds

Ok. So Basically, I have a sword sprite that I want to appear once every 2-5 seconds if a variable is true, then disappear after a second. I put this in a function called attack. The problem is,if I try to put attack(); into the update function, it spawns a ton of them! I need only one to spawn at a time! My code:

function attack() { if (isHit == true) { Destroy(GameObject.Find(“sword”)); WaitForSeconds(Random.Range(2,5)); Instantiate(sword,transform.position, Quaternion.identity); WaitForSeconds(2); Destroy(GameObject.Find(“sword”)); } }

How do I run this every 2-5 seconds with only one appearing at a time? I need to know this quick because I want to get a small demo done in a few days

Well, you only call attack once. If you call it from a key or something, look in the script reference for a pulse type call, rather than a constant firing call every update. If you aren’t using a key, create a bool and then test for it. I don’t use javascript, but create a variable bool called startAttack or something, then if(!startAttack){attack();startAttack = true;} when the attack is done, change it back to false.

I would recommend using a while statement if you want an infinite loop. Let me know if you need something different.

edit: Not sure if you’re trying to show and hide the sword through just this code? Could do something like var swordVisible : boolen; Then every time the sword code is called use this code swordVisible = !swordVisible; which will switch the variable from true to false if it’s true or false to true if it’s false. Also add an if statement for if(swordVisible) { //show sword else { //hide sword } }

var swordActive : boolean = true;

function Start () {

    sword();

}

function sword () {

    while(swordActive) {
        WaitForSeconds(Random.Range(2,5));
        //Call code for sword
    }
 
}

Yeah, it’s way cheaper and better to simply disable the sword’s renderer and collider than it is to instantiate and destroy it every attack.

Is there an easy way to do that without having to make a seperate script for the sword?

Just attach it to the attack script and make sure to asign the GetComponent in the Awake function. GetComponent is also expensive, but its no biggie if it is only called at start up.

Ok, but now the renderer wont enable itself or disable itself at all

function Awake() {
var swordCollider : UnityEngine.Collider2D;
swordCollider = GetComponentInChildren(Collider2D);
var swordRender : UnityEngine.Renderer;
swordRender = GetComponentInChildren(Renderer);
}
//Attacking Function*/
function attack() {

if (isHit == true) {
sword.renderer.enabled = false;
WaitForSeconds(Random.Range(2,5));
sword.renderer.enabled = true;
WaitForSeconds(2);
sword.renderer.enabled = false;
}
}