So, I have these enemies that walk left to right, depleting the health of the player. Problem is that whenever I click down a button this can destroy multiple enemies at the same time (no good). Using the picture below, if I press the A button, it should only destroy the first (A) enemy, then if I press it again it will destroy the next (A) character. I am unsure of how to implement this and was wondering what you guys think would be the best approach. 2DRaycasts? Triggers/Colliders? Something else? I’ve tried multiple ideas but to no avail, im sure you guys are smart enough to figure it out though… Thanks for the help!
You can store the same tag game objects in a list. If you spawn them in a script, you can do it in the script or assign them in the inspector to the list. Afterward, every time a key is pressed, you only pull the game object at the index zero and destroy it. Of course, you need to pay attention to your spawn order/assignment order in this solution. I know it is not a fancy solution but simple and time saver.
I think the best approach would be to use a c# List composed of these game objects. This way, you can iterate through all the current game objects on the screen and destroy only 1 game object.
Here is some pseudo-code…ish:
public List<GameObject> currObjs = new List<GameObject>();//list of current objects on screen
/*when gameobject spawned on screen*/
currObjs.Add(instantiatedObject);
/*Calling Method Every Time User Presses Button*/
void Update(){
if(Input.GetKeyDown(KeyCode.inputKey))
FindDestroyObj(inputKey);
}
/*this would check if you can destroy object on screen*/
private void FindDestroyObj(var inputKey){
foreach(GameObject obj in currObjs){
if(obj.GetComponent<ObjScript>().hasButton(inputKey)){//get object's script and call method to check if it can be destroyed
var tempObj = obj;//make sure this points to original 'obj'
currObjs.Remove(obj);//remove object from List
Destroy(tempObj);//this may cause some issues if temp not point correctly
break;//stop search and continue game
}
}
}
/*-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-==-*/
/*this would be in your game object script (the ones you want to destroy)
-Checks if the input corresponds to this objects'*/
public bool hasButton(var inputKey){
return thisInputKey==inputKey;
}
It would be more efficient if it were a hash table, so instead of looking through the entire list, you would only look in a possible place where it can be with that button type (if that makes any sense).
Let me know if you decide to code this out, I would love to help
@3kWikiGames