Does not Destroy instance of Game Object
I tried to destroy the instance of the game object but it just doesnt work. Basically I am trying to create instances of cloud and lightning which strikes the player at random intervals. I assigned the cloudAndLightning gameobject to be my prefab which is my cloud and lightning game objects. HELPPPP!!!!
public class KillObjectGenerator : MonoBehaviour {
public float randomTimeDelay;
public GameObject cloudAndLightning;
private Vector2 newPosition;
public float spawnTime = 3.0f;
public bool isSpawned = false;
private float randomX;
private float x;
private float y;
public GameObject justDisappearAlr;
void Start()
{
randomTimeDelay = Random.Range(3.0f, 6.0f);
// Start calling the Spawn function repeatedly after a delay.
InvokeRepeating("Generator", randomTimeDelay, spawnTime);
}
void spawnNewPosition()
{
float randomX = Random.Range(-4.7f, 3.6f);
float y = 4.3f;
newPosition = new Vector2(randomX, y);
}
public void Generator()
{
GameObject justDisappearAlr = (GameObject)Instantiate(cloudAndLightning, newPosition, Quaternion.identity);
isSpawned = true;
Debug.Log("Spawned a kill object!");
}
void OnCollisionExit2D(Collision2D col)
{
if(col.gameObject.tag == "gameObject")
{
Destroy(justDisappearAlr);
Debug.Log("KILLED YOU!");
isSpawned = false;
}
}
}
Answer by jmonasterio · Dec 10, 2015 at 03:37 PM
Check out line 32:
GameObject justDisappearAlr = (GameObject)Instantiate(cloudAndLightning, newPosition, Quaternion.identity);
You're making a new local variable called justDisappearAlr with the same name as your member variable on line 12.
I think you need to remove that "GameObject" type at the beginning of line 32, so you have:
justDisappearAlr = (GameObject)Instantiate(cloudAndLightning, newPosition, Quaternion.identity);
Answer by Holy_Crapf · Dec 10, 2015 at 11:40 PM
@heyhujiao Well the problem is you aren't using the OnCollisionExit2D method for each instantiated gameobject, you're using it for whatever this script is attached to. What you need to do is create a new script with your OnCollisionExit2D method, and have it attached to the cloudAndLighting prefab.
If you need to have the isSpawned changed to false, you can just do this:
void Update()
{
if(isSpawned)
{
//Checking if the global variable justDisappearAlr is destroyed.
if(justDisappearAlr == null)
{
isSpawned = false;
}
}
}
Also, just use your global variable for instantiating. No reason to create a local one.
Your answer
Follow this Question
Related Questions
Unity2D Destroy doesn't get rid of game objects,Gameobject Destroy not destroying object 0 Answers
Trigger on two static players (collider 2D) 0 Answers
2D Collision Problems... 0 Answers
Grid-based 2D game (turn based): How should I get started? 1 Answer
I need a help with the score system in my game. Any help will be greatly appreciated. 1 Answer