How do you change a variable in another gameobjects script

ok so basically im making a game wher the player shoots arrows and other projectiles
now when these projectiles enter the game objects collider they destroy themselves and they are also supposed to lower the enemys health. the enemies health is a variable in its script. now how do i do that.
heres what im doing
private void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag(“Wall”))
{

        gameObject.SetActive(false);
        
    }
    if (other.CompareTag("Enemy"))
    {
        other.Health = other.Health - ;
        gameObject.SetActive(false);
       
    }

other.Health doesn’t work because other is a Collider2D.
What you want to do is:

//Assuming your enemy script is called Enemy
Enemy enemy = other.GetComponent<Enemy>();
enemy.Health = enemy.Health - 1;

A couple things:

  • gameObject.SetActive(false) doesn’t actually destroy an object. It just sets it invisible in the Hierarchy. You’ll want to use Destroy(gameObject) instead.

  • Which object is this script on? Is it on the arrow? If it is, the code does make sense, however, I’m not exactly certain how it compiles, because line 6 is invalid. Presumably, you meant to use a decrement operator (–) rather than just the one minus sign. However, this won’t even resolve the identifier Health, because other in this case is a Collider2D. You’ll want to do other.GetComponent<ScriptTypeContainingHealthVariable>().Health-- or decrease by an amount you can set as a property of the arrow. Maybe it’s a training arrow, so you can decrease health by 0. Or maybe it’s a powerful arrow with a nasty looking arrowhead, so you might subtract 10 or more. Up to you:

    public class Arrow : MonoBehaviour {
    public int m_damage = 10;

     private void OnTriggerEnter2D(Collider2D other) { 
         if (other.CompareTag("Wall")) {
              Destroy(gameObject);
         }
    
         if (other.CompareTag("Enemy"))
         {
              other.GetComponent<ScriptTypeContainingHealthVariable>().Health = other.GetComponent<ScriptTypeContainingHealthVariable>().Health - m_damage;
              Destroy(gameObject);
         }
     }
    

    }