Question by
DjFrex · Mar 23, 2016 at 03:05 PM ·
c#instantiateprefabdestroy
Instantiate and destroy an object with the same key
Hi guys, I'm having some trouble with the following code. I want that on the first "Fire1" pression, a CarLight is instantiated, and on the second pression it is destroyed. Anyway "FixedUpdate" function run every line of the code on each frame, so the result is that my light is created and destroyed in the same frame. How can I avoid this issue? Thank you a lot.
public GameObject brakeLights;
public GameObject carLights;
public Transform brakeSpawn;
public Transform lightSpawn;
private bool created;
private GameObject instantied;
void Start()
{
created = false;
}
public void FixedUpdate()
{
if (!created) {
if (Input.GetButtonDown ("Fire1")) {
instantied = (GameObject)Instantiate (carLights, lightSpawn.position, lightSpawn.rotation);
created = true;
Debug.Log ("light created");
instantied.transform.parent = this.transform;
}
}
if (created) {
if (Input.GetButtonDown ("Fire1")) {
Destroy (instantied);
created = false;
Debug.Log ("light destroyed");
}
}
}
}
Comment
Best Answer
Answer by Hellium · Mar 23, 2016 at 03:07 PM
You should not use FixedUpdate to manage user input, but for physics only.
Don't forget one of the most important rule in coding : KISS = Keep it stupid simple
private void Update()
{
if (Input.GetButtonDown ("Fire1"))
{
if( instantied )
{
Destroy( instantied ) ;
}
else
{
instantied = (GameObject)Instantiate (carLights, lightSpawn.position, lightSpawn.rotation);
instantied.transform.parent = this.transform;
}
}
}
Lol, much more simple than i thought.. I think it's obvious i'm a beginner, thank you a lot, it works great!