Spawn an object and destroy it

I am beginner at scripting, and i want to make a prefab spawn, and then be destroyed after some time. I know that i need to use a public float so i can change the script, but how can i spawn the object?

void SpawnAndDestroy(GameObject prefab, float delay)
{
GameObject newGO = Instantiate(prefab) as GameObject;
Destroy(newGO, delay);
}

well in order to spawn a prefab you would need to use instantiate and then use Yield WaitForSecond in order to wait a some time and then destroy it afterwards using Destroy

here is an example

//first declare all the variables
var Object : GameObject; //the prefab you want to spawn
var Spawn : Transform; //the point you want it to spawn at
var WaitTime = 3; // time it has to wait untill it gets destroyed

function Start() {
//because the functions Start and Update can't be corroutines you need 
// to make another function in order to use Yield WaitForSeconds
Spawn(); // the other function

}

function Spawn() {

if(Input.GetButton("Fire1")) { // action that needs to be done in order to
// instantiate a new prefab

Instantiate(Object, Spawn.position , Spawn.rotation);
// instantiates a new prefab (Instantiate(objecttospawn, spawnposition. 
// spawnrotation)
Yield WaitForSeconds(WaitTime);
// makes the code wait WaitTime and then resumes
Destroy(gameObject);
// destroys the game object

}

}

I’m didn’t have the time to check for errors but this should work if you get any errors you can say it and I’ll correct it

I advice you however to look up all the things I have declared to get a better vision of how to use them

have great day

This is how you should do :

 function SpawnAndDestroy(prefab: GameObject, waitTime : float)
    {
         GameObject obj = Instantiate(prefab);
         yield WaitForSeconds (waitTime);
         Destroy(obj);
    }

And then you call the function like this:

var Prefab : GameObject;
var Delay : float;

function Start()
{
    StartCoroutine(SpawnAndDestroy(Prefab, Delay));
}

For more information, visit this link.

// first declare all the variables
var Object : GameObject; // object to spawn
var Spawn : Transform; // object it spawns at
var WaitTime = 3; // time objects waits till it gets destroyed

function Start() {
Spawn(); // you can't use corroutines in the Start and Update function so we
// call a new function in order to use Yield WaitForSeconds

}

function Spawn() {
Instantiate(Object, Spawn.position, Spawn.rotation);
/* Instantiate is used to make object or something else spawn.
Instantiate(thingtospawn, positionitspawnsat, rotationitspawnin) */
Yield WaitForSeconds(WaitTime);
// stops the code for a time and then resumes it but because its a
// corroutine it can't be in the Update and Start functions
Destroy(gameObject);
//destroys the gameobject the script is attached to

}

I haven’t checked for errors but this should work.
if not tell me and i’ll fix the error

have a great day