Search Unity

GameObjects deleting inconsistently

Discussion in 'Windows' started by PotassiumBromide, Feb 5, 2021.

  1. PotassiumBromide

    PotassiumBromide

    Joined:
    Jan 18, 2018
    Posts:
    2
    I'm fairly new to both programming and Unity, and am making a simple clicker game. One of the items I've added moves across the bottom of the screen to pickup any of the bananas that are falling. When the bananas collide with the item, the score is properly added. The banana itself, however, only gets deleted sometimes. I can't figure out what's causing the edge case, but it seems like the more items I have, the more likely it is to actually delete the bananas on contact. Here's the code attached to the items that is supposed to delete the bananas.
    Code (CSharp):
    1. public class BasketMovement : MonoBehaviour
    2. . . .
    3.  
    4.     private void OnTriggerEnter2D(Collider2D other)
    5.     {
    6.         if (other.gameObject.CompareTag("Banana"))
    7.         {
    8.             ScoreManager.instance.ChangeScore(bananaValue);
    9.             Destroy(GameObject.FindWithTag("Banana"), 0.1f);
    10.             Debug.Log("Destroyed Banana");
    11.         }
    The debug log triggers without issue, it's just the destroy line that is inconsistent.

    I should also note that I have another script for clicking the bananas manually using almost identical code, and it works fine.
     
  2. rebecca_b

    rebecca_b

    Unity Technologies

    Joined:
    Jul 9, 2018
    Posts:
    7
    Are you sure it's not that some other banana than the one you're expected is being destroyed?

    From the FindWithTag documentation:
    This method returns the first GameObject it finds with the specified tag. If a scene contains multiple active GameObjects with the specified tag, there is no guarantee this method will return a specific GameObject.​