Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Bug If statement inside of foreach loop not running

Discussion in 'Scripting' started by grqphical, Jan 22, 2022.

  1. grqphical

    grqphical

    Joined:
    Jul 15, 2021
    Posts:
    10
    Hello,

    So I am trying to implement a rudimentary inventory system where if the player collides with a dropped gun it will destroy the dropped gun and instantiate the same gun as a child object of the player. My system uses a foreach loop to loop through a list of guns (gunList) and checks to see if the collided game object's name is equal to the gun in gunList. But for some reason the if statement I have to check this isn't firing. Here is my code and it's attached to the player

    Code (CSharp):
    1. private void OnTriggerEnter2D(Collider2D other)
    2.     {
    3.         foreach (GameObject gun in gunList)
    4.         {
    5.             if (other.name == gun.name)
    6.             {
    7.                 Debug.Log("Same Gun");
    8.                 Instantiate(gun, transform.position, transform.rotation, transform);
    9.             }
    10.         }
    11.        
    12.         Destroy(other.transform.parent.gameObject);
    13.        
    14.     }
     
  2. alexeu

    alexeu

    Joined:
    Jan 24, 2016
    Posts:
    257
    Put a Debug.Log() before the foreach () to see if OnTriggerEnter2D() matches
     
    Bunny83 likes this.
  3. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    3,528
    Is the "dropped" gun by any chance an instantated prefab instance? If so, by using Instantiate the object's name gets an annoying " (clone)" suffix to its name. To avoid / remove that suffix you would need to restore the old name when you instantiate your dropped gun.

    Something like that may work:
    Code (CSharp):
    1. GameObject newDrop = Instantiate(gunDropPrefab);
    2. // restore original name / remove "(clone)" suffix
    3. newDrop.name = gunDropPrefab.name;

    Though I would also suggest you add a Debug.Log and simply print out the two names to see why they don't match. Because when an code block that is covered by an if statement does not run, the condition has to be false. In other words your string comparison is always false. So one or either both strings may not represent what you think they should.
     
    grqphical and alexeu like this.
  4. grqphical

    grqphical

    Joined:
    Jul 15, 2021
    Posts:
    10
    Tried that. The loop works fine its just the if statement
     
  5. alexeu

    alexeu

    Joined:
    Jan 24, 2016
    Posts:
    257
    So as Bunny83 said and in other words : if you never enter the if statement, that means it Always returns False.
    try what he suggested about other.name & gun.name.
     
    Bunny83 likes this.