- Home /
Question by
danutdragusan · Dec 01, 2017 at 08:14 AM ·
c#script.
How to destroy prefab to end the game?
When player hit space and destroy prefab12 game should be ended but I don,t know how to do that...
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RandomScripts : MonoBehaviour {
public GameObject prefab1, prefab2, prefab3, prefab4, prefab5;
GameObject prefab11,prefab12,prefab13,prefab14,prefab15;
public float t = 0.5f;
public float spawnRate = 2f;
float nextSpawn = 0f;
int whatToSpawn;
// Update is called once per frame
void Update()
{
if(Time.time > nextSpawn)
{
whatToSpawn = Random.Range(1, 6);
switch(whatToSpawn)
{
case 1:
prefab11 = Instantiate(prefab1, transform.position, Quaternion.identity)as GameObject;
Destroy(prefab11, t);
break;
case 2:
prefab12 = Instantiate(prefab2, transform.position, Quaternion.identity) as GameObject;
Destroy(prefab12, t);
break;
case 3:
prefab13 = Instantiate(prefab3, transform.position, Quaternion.identity) as GameObject;
Destroy(prefab13, t);
break;
case 4:
prefab14 = Instantiate(prefab4, transform.position, Quaternion.identity) as GameObject;
Destroy(prefab14, t);
break;
case 5:
prefab15 = Instantiate(prefab5, transform.position, Quaternion.identity) as GameObject;
Destroy(prefab15, t);
break;
}
nextSpawn = Time.time + spawnRate;
}
if (Input.GetKeyDown(KeyCode.Space))
{
Destroy(prefab12);
}
}
}
Comment
Ins$$anonymous$$d of destroying a prefab, did you consider to just deactivate that gameobject in hierarchy?
Two reasons for this, First, It consumes less memory to simply disable to gameobject rather than destroying it. And second, with the disabled/inactive gameobject, you could simply re-enable it in-case if you need it, rather than instantiating a new one.
If prefab12 is destroyed or dezactivated you win...
Your answer