Search Unity

Question (Important) If one enemy is shot, it only effects the first enemy in the scene

Discussion in '2D' started by CarricxColl, Jun 2, 2023.

  1. CarricxColl

    CarricxColl

    Joined:
    Mar 23, 2023
    Posts:
    4
    If i shoot an enemy that isn't the first one that was created, it effects the first one that was created, and no other enemies. I have attached the script for the enemies in question. This is for a project due next week, so a reply would be much appreciated!
     

    Attached Files:

  2. Atomiz2002

    Atomiz2002

    Joined:
    Feb 2, 2020
    Posts:
    14
    Not much I can figure out personally. All I can say is that a general rule of thumb is to avoid static fields. In the "kngiht" class you have a static "kngiht" instance field which is shared across all gameobjects with the said script. Technically the last gameobject with this script reach the Awake method will be the one the instance field is set to. That alone is probably not enough to resolve your issue but at least its something to get started off of.
     
  3. CarricxColl

    CarricxColl

    Joined:
    Mar 23, 2023
    Posts:
    4
    Thank you. How would i go about doing it without the static field?
     
  4. CarricxColl

    CarricxColl

    Joined:
    Mar 23, 2023
    Posts:
    4
    I was using the instance so i could access the kngiht script from this script here
     

    Attached Files:

  5. Atomiz2002

    Atomiz2002

    Joined:
    Feb 2, 2020
    Posts:
    14
    You can simlpy get the component of the "enemy" directly. Try
    if (collision.TryGetComponent(out kngiht instance)) instance.KnightVulnerable();
    Then check if you need to compare the tags this way or you can directly check for a component since you would need it either way.
     
  6. CarricxColl

    CarricxColl

    Joined:
    Mar 23, 2023
    Posts:
    4
    It fixed it! Thank you so much
     
    Atomiz2002 likes this.