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

Can't modify variable on another game objects script?

Discussion in 'Scripting' started by thevvulf, Aug 23, 2021.

  1. thevvulf

    thevvulf

    Joined:
    Oct 31, 2020
    Posts:
    36
    Code (CSharp):
    1. void Update()
    2.     {
    3.         targetedEnemyHealth = targetedEnemy.GetComponent<EnemyMain>().health;
    4.         transform.LookAt(targetedEnemy.transform);
    5.         transform.Translate(Vector3.forward * Time.deltaTime * laserSpeed);
    6.         Debug.Log(targetedEnemyHealth);
    7.         if(Vector3.Distance(targetedEnemy.transform.position, transform.position) <= 0.25f){
    8.             targetedEnemyHealth -= laserDamage;
    9.             Destroy(gameObject);
    10.         }
    11.     }
    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.
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,144
    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.
     
    Last edited: Aug 23, 2021
    Vryken likes this.
  3. thevvulf

    thevvulf

    Joined:
    Oct 31, 2020
    Posts:
    36
    i love you so much this worked perfectly