,Keeping a variable between scripts constant?

I am having trouble keeping a variable between 2 scripts the same. I have one deriving from the other, yet one of the variables is treated as a different int.

First one

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class Warmth : MonoBehaviour

    //Warmth Script, first one

{
    public int heatLvl; // = 100f;
    public string sceneName;

    void Start()
    {
        InvokeRepeating("decreaseHeat", .25f, .25f);
    }

    void decreaseHeat()
    {
        if (heatLvl > 0)
        {
            heatLvl -= 1;
        }
    }
    void FixedUpdate()
    {
        Debug.Log(heatLvl);

        if (heatLvl <= 0)
        {
            SceneManager.LoadScene(sceneName);
        }

    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        heatLvl = 100;
    }

}

second one

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Health : Warmth {

    //Health script, second one

    private const float MAX_HEALTH = 100f;

    public Warmth warmth;

    public float health = MAX_HEALTH;

    private Image healthBar;

    private void Start()
    {
        healthBar = GetComponent<Image>();
        InvokeRepeating("decreaseHeat", .25f, .25f);
    }

    private void FixedUpdate()
    {
        healthBar.fillAmount = health / MAX_HEALTH;
        health = heatLvl;
    }

}

Let me guess. You’ve attached both of these to the same game object probably.


The thing is, you don’t understand what is the inheritance and where and how it should be used. Yes, inheritance is a good thing when you want some similar classes to have mutual methods, but you can’t have both the base class and its ancestor at the same object. When you do this, you actually get one Health class which is also the Warmth and you have another Warmth which is just warmth.


By making a class inherit from another class you actually make it both the Health and the Warmth at the same time, and when you initialize a Health component you automatically initialize an instance that has its own Warmth variables independently of the other Warmth component.


Inheritance is a cool feature but you have to understand what is it actually and how does it work.
Read some books about object oriented programming, there are awesome ones written specifically for novices, e.g. “C# 7.0 All-in-one for dummies” by John Paul Mueller was one of the books I’ve read when I learned programming, it’s very very good book.