Can't modify variable on another game objects script?

void Update()
    {
        targetedEnemyHealth = targetedEnemy.GetComponent<EnemyMain>().health;
        transform.LookAt(targetedEnemy.transform);
        transform.Translate(Vector3.forward * Time.deltaTime * laserSpeed);
        Debug.Log(targetedEnemyHealth);
        if(Vector3.Distance(targetedEnemy.transform.position, transform.position) <= 0.25f){
            targetedEnemyHealth -= laserDamage;
            Destroy(gameObject);
        }
    }

All its supposed to do is get the public float variable “health” from “targetedEnemy”. Then, once its within range, remove “laserDamage” (a public float set to 1) from targetedEnemyHealth. I know it recognizes the variable, since I put a Debug.Log in there and it worked fine when changing the health value around. But for some reason, it won’t modify the variable. I’m very new to unity, so sorry if its a super beginner mistake.

This is simply a case where you may be unfamiliar with reference types vs value types.

health is probably an int, which is a value type. This means when you set targetedEnemyHealth = to health, it simply copies the value over. In this case, it does not change the value of health. It changes the value of targetedEnemyHealth.

The most straightforward fix is to not have your other scripts do direct damage. Instead, your EnemyMain script should have a TakeDamage method. Then, you get a reference to the EnemyMain component on your targetedEnemy and call the TakeDamage method, passing in the amount of damage you want to deal. This also let’s your EnemyMain script check it’s health and see if it should die or not.

This way, your EnemyMain script takes care of updating it’s own health value. This will come with experience on how to write better classes in the future.

Just note that doing this in Update may not be the best way, just because you’d end up with repeated GetComponent calls. But the fix will still work if you do this from Update at least.

1 Like

i love you so much this worked perfectly