- Home /
Destroy(clone) not destroying the instantiated prefab
I'm trying to destroy an instantiated prefab but it isn't doing anything.
Here's my code:
void Update () {
if (P1notSpawned)
{
GameObject player1 = (GameObject)Instantiate(P1, spawnPoint1.position, spawnPoint1.rotation);
P1notSpawned = false;
}
if (P2notSpawned)
{
GameObject player2 = (GameObject)Instantiate(P2, spawnPoint2.position, spawnPoint2.rotation);
P2notSpawned = false;
}
if (P1Life <= 0)
{
Destroy(player1);
P1Life = 5;
for (int i = 0; i < p1Sticks.Length; i++)
{
if (P1Life > i)
{
p1Sticks[i].SetActive(true);
}
else
{
p1Sticks[i].SetActive(false);
}
}
}
if (P2Life <= 0)
{
Destroy(player2);
P2Life = 5;
for (int i = 0; i < p2Sticks.Length; i++)
{
if (P2Life > i)
{
p2Sticks[i].SetActive(true);
}
else
{
p2Sticks[i].SetActive(false);
}
}
}
}
The Destroy(player1) and Destroy(player2) aren't actually destroying the instantiated prefabs.
Answer by TreyH · May 21, 2018 at 05:53 PM
You seem a little confused about scope. Those references do not exist as you've written them and I doubt this compiles at all.
Before you continue with Unity, you should check out a few of the official tutorials. These help familiarize people with C# and Unity in general, which sounds like you might want to consider:
https://unity3d.com/learn/tutorials/topics/scripting/coding-unity-absolute-beginner
For your situation, you need to preserve those references:
private GameObject player1;
private GameObject player2;
void Update () {
if (P1notSpawned)
{
this.player1 = (GameObject)Instantiate(P1, spawnPoint1.position, spawnPoint1.rotation);
P1notSpawned = false;
}
if (P2notSpawned)
{
this.player2 = (GameObject)Instantiate(P2, spawnPoint2.position, spawnPoint2.rotation);
P2notSpawned = false;
}
if (P1Life <= 0)
{
Destroy(this.player1);
P1Life = 5;
for (int i = 0; i < p1Sticks.Length; i++)
{
if (P1Life > i)
{
p1Sticks[i].SetActive(true);
}
else
{
p1Sticks[i].SetActive(false);
}
}
}
if (P2Life <= 0)
{
Destroy(this.player2);
P2Life = 5;
for (int i = 0; i < p2Sticks.Length; i++)
{
if (P2Life > i)
{
p2Sticks[i].SetActive(true);
}
else
{
p2Sticks[i].SetActive(false);
}
}
}
}
This works perfectly, thanks!
I will check those tutorials out.