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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Inherited Variable in Subclass not Using Value in Inspector

Discussion in 'Scripting' started by Galactasm, Apr 10, 2020.

  1. Galactasm

    Galactasm

    Joined:
    Feb 18, 2019
    Posts:
    3
    Hello,

    I created a class, Entity, which inherits from MonoBehavior. This class has a public float called health.

    I created another class called player which inherits from Entity.

    The variable health displays as expected in the inspector when selecting an object with the player script attached to it. However, when I set the value in the inspector, the value is ignored at runtime and health ends up being 0. I'm not sure why the value in the inspector is being ignored.
     
  2. Suddoha

    Suddoha

    Joined:
    Nov 9, 2013
    Posts:
    2,824
    Unfortunately your description doesn't really help. There's surely a bug in your code, and in order to find it, we need to see the code. Please add the relevant code or a minimal example that doesn't work as you expect.
     
  3. Galactasm

    Galactasm

    Joined:
    Feb 18, 2019
    Posts:
    3
    Code (CSharp):
    1. // inside the LivingEntity script
    2. public class LivingEntity : MonoBehavior
    3. {
    4.   public float startingHealth;
    5.   protected float health;
    6.  
    7.   protected virtual void Start()
    8.   {
    9.     health = startingHealth;
    10.   }
    11. }
    12.  
    13. // inside the player script
    14. public class Player : LivingEntity
    15. {
    16.   protected override void Start()
    17.   {
    18.     Base.Start()
    19.     // other player stuff
    20.   }
    21. }
    I've created a gameobject in the editor and attached the player script to it. The variable startingHealth appears in the inspector. I set it to something like 10. However when the game starts startingHealth and health are 0. I've confirmed that calling Base.Start() in the Player class calls the Start function in LivingEntity, but once again the startingHealth value is 0 when it gets called for some reason.
     
  4. Galactasm

    Galactasm

    Joined:
    Feb 18, 2019
    Posts:
    3
    Ok, I'm really stupid, I had 2 Player scripts attached to the player object, one of them was setting the startingHealth to 0............ I'll see myself out lol.