- Home /
Destroy(gameObject) does not work
I am trying to make a rhythm game, this code is to destroy the arrows when clicking a specific button when passing a specific place but when clicking the button the arrow is not destroyed, this is only part of the code but I suppose that here it is the problem
if (Input.GetKeyDown(KeyCode.RightArrow))
{
if (adentro)
{
GameObject.Find("Casilla").GetComponent<logicaCuadro>().puntaje++;
GameObject.Find("Casilla").GetComponent<logicaCuadro>().texto.text = "Score: " +
GameObject.Find("Casilla").GetComponent<logicaCuadro>().puntaje.ToString();
Destroy(gameObject);
}
}
Answer by VoidPhoenix96 · Dec 28, 2020 at 08:58 PM
One possibility is that the code never runs the part with the destroy function. You can test this with Debug.Log(); If in the console you see what your wrote in the Debug.Log(); when the button is pressed, that means that the code is running. If it is not running try rewriting it in a different way.
I hope this helps.
Answer by sacredgeometry · Dec 28, 2020 at 09:00 PM
Just a word of warning. From the look of your code its pretty apparent that you are going to have some serious problems making a rhythm game. So firstly and genuinely good luck with it.
Secondly Find is really expensive and you are not only calling it once but are calling it (and get component) three times to get the same object. If you really need to call it at all store the returned value in a variable (ideally one that is scoped so that you only need to find it once per runtime) i.e.
public GameObject Casilla { get; set; }
public logicaCuadro LogicaCuadro { Get; Set; }
void Start()
{
Casilla = GameObject.Find("Casilla")
LogicaCuadro = casilla?.GetComponent<logicaCuadro>();
}
Thirdly. Which gameObject are you trying to destroy? The one this code is on? What is adentro
and is it being set to true?
Fourthly. Never call destroy unless absolutely necessary. I would imagine you are using multiple instances of this item that you are destroying and instantiating them again and again. Just pool and reuse them. A rhythm game is very time sensitive managed languages aren't great for that but you are only making it worse by asking the GC to kick in over and over again.
Fifthly the casing convention for classes in C# is Pascal Casing. Components are Classes so naming them where each word starts with a capital letter will stop confusion.
Your answer
Follow this Question
Related Questions
using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers
Problem with timed code-execution (audioplay and object destruction) 1 Answer
Trying to make a simple inventory: 0 Answers
Why Destroy(gameobject) fail once in a while? 2 Answers
Issues with destroying a game object 2 Answers