- Home /
The question is answered, right answer was accepted
Destroy a gameobject from an index of a list, destroy all same gameobjects right after it, why ?
Hi there ! Here is my configuration : I got an array of 7 prefabs. I instantiate continually and randomly gameobjects from this array and add it on a list. 7 buttons from the pad controller are configured to destroy the gameobjects. For now, my script work well : gameobjects runs in the scene, from right to left. If I put one of the buttons it destroy the first instantiated gameobject (due to the list index). But what I don't understand is why, when 2 or more same gameobjects are next to each other's, the button destroy all those same gameobjects.
Here is the code :
if (Input.GetButton("yButton"))
{
if (NoteList[0] == Bnote)
{
Destroy (NoteList[0].gameObject);
NoteList.RemoveAt(0);
}
In my point of view, NoteList[0].gameObject, shouldnt destroy NoteList[1/2/3/...].gameObject, nope ?
Answer by Irrgeist · Jun 10, 2018 at 01:43 AM
Try using Input.GetButtonDown("key")
instead of GetButton
.
As the documentation states (https://docs.unity3d.com/ScriptReference/Input.GetButtonDown.html):
Returns true during the frame the user pressed down the virtual button identified by buttonName.
GetButton
probably fires multiple times each frame. You have to press the button really fast, sinceGetButton
always returns true while the button is pressed. Since there are a lot of frames processed each second, more objects get deleted.GetButtonDown fires only in one frame and also:
It will not return true until the user has released the key and pressed it again.
Answer by ludwu · Jun 10, 2018 at 09:21 AM
Yeah saw my misstake yesterday thank you so much ! But now got the same problem with d pad I use like buttons. Tried many things to make it work like buttons down but nothing work... Any ideas ?
Finally found the way, below is the code for vertical axis :
private bool v_isAxisInUse = false;
if (Input.GetAxisRaw("dpadAxisV") > 0)
{
if (v_isAxisInUse == false)
{
if (NotesList[0] == Dnote)
{
Destroy (NotesList[0].gameObject);
NotesList.RemoveAt(0);
}
v_isAxisInUse = true;
}
}
if (Input.GetAxisRaw("dpadAxisV") < 0)
{
if (v_isAxisInUse == false)
{
if (NotesList[0] == Fnote)
{
Destroy (NotesList[0].gameObject);
NotesList.RemoveAt(0);
}
v_isAxisInUse = true;
}
}
if (Input.GetAxisRaw("dpadAxisV") == 0)
{
v_isAxisInUse = false;
}
Do the same for horizontal axis with a private bool v_isAxisInUse = false;
Follow this Question
Related Questions
Instantiate an object and place it on a list. 1 Answer
Destroy and rebuild game objects from lists 1 Answer
A node in a childnode? 1 Answer
Instantiate prefab and Add to a Generic List 2 Answers
How to put gameObjects to the list? 4 Answers