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

2 scripts i need to use inheritance with

Discussion in 'Scripting' started by AxelDriesenMct, Mar 9, 2015.

  1. AxelDriesenMct

    AxelDriesenMct

    Joined:
    Feb 20, 2015
    Posts:
    8
    Hello, I have this assignement at school. I need to make a game by using c# and inheritance. I have a script called flashlight and another one called battery. The flashlight contains the keybuttondown (f) component and sound effects. The battery contains a Gui element to show the batterybar , and all code for draining the battery.

    Now here is my question how can i make inheritance with these scripts? or isn't it possible?


    ----------------------------------------------------------------------------------------------------------------------------------------
    this one is flashlight
    ----------------------------------------------------------------------------------------------------------------------------------------

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class zaklamp : MonoBehaviour
    5. {
    6.  
    7.   public Light lightSource;
    8.   public bool on = true;
    9.  
    10.   void Start()
    11.   {
    12.     lightSource = GetComponentInChildren<Light>();
    13.   }
    14.  
    15.   void Update()
    16.   {
    17.     if (on)
    18.       lightSource.light.enabled = false;
    19.     else if (!on)
    20.       lightSource.light.enabled = true;
    21.     if (Input.GetKeyDown(KeyCode.F))
    22.       on = !on;
    23.     if (Input.GetKeyDown(KeyCode.F))
    24.       audio.Play();
    25.   }
    26. }
    ----------------------------------------------------------------------------------------------------------------------------------
    This one is batterylife
    ----------------------------------------------------------------------------------------------------------------------------------
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class batterylife : zaklamp {
    5.  
    6.   private float lightDrain = 0.1f;
    7.   private static float batteryLife = 0.0f;
    8.   private float maxBatteryLife = 2.5f;
    9.  
    10.  
    11. private static float batteryPower = 1f;
    12.  
    13.   float barDisplay = 0;
    14.   Vector2 pos = new Vector2(20,40);
    15.   Vector2 size = new Vector2(60,20);
    16. public Texture2D progressBarEmpty;
    17. public Texture2D progressBarFull;
    18.  
    19.  
    20.  
    21.     void Start () {
    22.     batteryLife = maxBatteryLife;
    23.     }
    24.  
    25.   static void AlterEnergy (int amount)
    26. {
    27.     batteryLife = Mathf.Clamp(batteryLife+batteryPower, 0, 100);
    28.  
    29. }
    30.    
    31.     // Update is called once per frame
    32.   void Update()
    33.   {
    34.  
    35.     if (on && batteryLife >= 0)
    36.     {
    37.       batteryLife -= Time.deltaTime * lightDrain;
    38.     }
    39.     if (on && batteryLife <= 0.4)
    40.     {
    41.       lightSource.light.intensity = 5;
    42.     }
    43.     if (on && batteryLife <= 0.3)
    44.     {
    45.       lightSource.light.intensity = 4;
    46.     }
    47.     if (on && batteryLife <= 0.2)
    48.     {
    49.       lightSource.light.intensity = 3;
    50.     }
    51.     if (on && batteryLife <= 0.1)
    52.     {
    53.       lightSource.light.intensity = 2;
    54.     }
    55.     if (on && batteryLife <= 0)
    56.     {
    57.       lightSource.light.intensity = 0;
    58.     }
    59.  
    60.  
    61.  
    62.     barDisplay = batteryLife;
    63.  
    64.     if (batteryLife <= 0)
    65.     {
    66.       batteryLife = 0;
    67.       on = false;
    68.     }
    69.  
    70.     if (Input.GetKeyDown(KeyCode.F))
    71.     {
    72.  
    73.       if (on)
    74.       {
    75.         on = false;
    76.       }
    77.       else if (!on && batteryLife >= 0)
    78.       {
    79.         on = true;
    80.       }
    81.  
    82.     }
    83.   }
    84.  
    85.  
    86.  
    87.  
    88.   void  OnGUI (){
    89.     // draw the background:
    90.     GUI.BeginGroup (new Rect (pos.x, pos.y, size.x, size.y));
    91.         GUI.Box ( new Rect(0,0, size.x, size.y),progressBarEmpty);
    92.         // draw the filled-in part:
    93.         GUI.BeginGroup (new Rect (0, 0, size.x * barDisplay, size.y));
    94.             GUI.Box ( new Rect(0,0, size.x, size.y),progressBarFull);
    95.         GUI.EndGroup ();
    96.     GUI.EndGroup ();
    97. }
    98. }
     
  2. Mr-Mud

    Mr-Mud

    Joined:
    Mar 8, 2015
    Posts:
    37
    It seems as though you have applied inheritance to the script already... That would imply that you can indeed apply inheritance to it. But I find the way you have implented it to be a bit peculiar; inheritance is used to make classes/scripts more specific. Something which works on batteries seems less specific than a flashlight, therefore I would swap them in the hierarchy. You can then have a MobilePhone also extend battery life, as could a Laptop and a Handdrill to name a few examples.

    Code (CSharp):
    1. using System;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4.  
    5. using UnityEngine;
    6.  
    7. public abstract class ChargedItem : MonoBehaviour
    8. {
    9.     private float _charge;
    10.     public float charge
    11.     {
    12.         get{return _charge;}
    13.         set
    14.         {
    15.             if (value!=_charge)
    16.             {
    17.                 //Keep the charge in the bounds 0 and maxCharge.
    18.                 _charge = Mathf.Clamp(value,0,maxCharge);
    19.             }
    20.         }
    21.     }
    22.  
    23.     [SerializeField]//Makes this field show up in the inspector.
    24.     private float _maxCharge;
    25.     public float maxCharge
    26.     {
    27.         get{return _maxCharge;}
    28.         set{_maxCharge = value;}
    29.     }
    30.  
    31.     //With a few exceptions, it will always be called by Unity.
    32.     protected virtual void Awake()
    33.     {
    34.         charge = maxCharge;
    35.     }
    36. }
    Code (CSharp):
    1. using System;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4.  
    5. using UnityEngine;
    6.  
    7. [RequireComponent(typeof(Light))]
    8. public class Flashlight : ChargedItem
    9. {
    10.     private Light _lightSource;
    11.  
    12.     protected override void Awake ()
    13.     {
    14.         base.Awake ();
    15.         //Cache the lightsource.
    16.         _lightSource = GetComponent<Light>();
    17.     }
    18.  
    19.     protected virtual void Update()
    20.     {
    21.         //Discharge while 'F' is pressed; recharge when it is released.
    22.         if (Input.GetKey(KeyCode.F))
    23.             charge-=Time.deltaTime;
    24.         else
    25.             charge+=Time.deltaTime;
    26.  
    27.         //Set the intensity of the lightsource as if it decays.
    28.         _lightSource.intensity = Mathf.Sqrt(charge / (Mathf.Abs(maxCharge) + 0.01f));
    29.     }
    30. }
    Lastly, I think that not all items need their charge to be shown on the screen. Therefore you could make that a seperate script, which can then be toggled seperately of the ChargedItem (mobiles and alike run out of energy, even if you don't see it). This is part of the Composition design pattern.
    Code (CSharp):
    1. using System;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4.  
    5. using UnityEngine;
    6.  
    7. [RequireComponent(typeof(ChargedItem))]
    8. public class ChargeDrawer : MonoBehaviour
    9. {
    10.     private ChargedItem _chargedItem;
    11.  
    12.     protected virtual void Start()
    13.     {
    14.         //Cache the reference to the object.
    15.         _chargedItem = GetComponent<ChargedItem>();
    16.     }
    17.  
    18.     protected virtual void OnGUI()
    19.     {
    20.         //Location of the bar which will be displayed.
    21.         Rect bar = new Rect(10,10, 200, 20);
    22.         GUI.Box(bar,"");
    23.         //Make sure the value which we use to divide is not 0.
    24.         bar.width *= _chargedItem.charge/(Mathf.Abs(_chargedItem.maxCharge)+0.01f);
    25.         GUI.backgroundColor = Color.green;
    26.         GUI.Box(bar,"", GUI.skin.button);
    27.     }
    28. }
     
    lordconstant likes this.
  3. AxelDriesenMct

    AxelDriesenMct

    Joined:
    Feb 20, 2015
    Posts:
    8
     
  4. Mr-Mud

    Mr-Mud

    Joined:
    Mar 8, 2015
    Posts:
    37
    Unless you are trying to have classes to inherit from themselves (or a descendant) - as that would be the same as you being your own father/mother; impossible - you can basically choose to inherit from any class that is not marked as sealed. So I would assume that you could do that... but why not let it inherit from something like "Item", and have the ChargedItem class (and its descendants) take care of batteries (which will probably be another Item that is lingering around).

    Maybe an example of how you should see Inheritance, helps you get a better grasp of the concept. During Biology classes, you probably have encountered something where you assign an things to a specific class:
    • Organism
      • Animal
        • Mammal
          • Cow
          • Dolphin
        • Bird
          • Ostrich
          • Goose
      • Plant
        • Tree
          • Oak
          • Elm
          • Birch
        • Flower
      • etc.
    This example (which might not be quite accurate) probably won't translate well in what you are trying to acchieve, but I think it should help you get a somewhat better understanding of the idea.

    Off topic: At first glance I thought that you accidentially quoted my post; there didn't appear to be any added content (this forum hides a part of the quote if it is long). So my advice is to keep comments on a post outside of that quote.
     
    AxelDriesenMct likes this.
  5. AxelDriesenMct

    AxelDriesenMct

    Joined:
    Feb 20, 2015
    Posts:
    8
    I don't know how this forum works yet but, thanks to you i am starting to understand inheritance. But its kinda hard to think of good ones when making a horrorgame.. But i think i can do it now halfway there! tyvm !
     
  6. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    This is wrong. Inheritance implies a is a relationship. Your battery inherits from flashlight. Let me say that again:

    A battery is a flashlight.

    This does not compute. A flashlight has a battery. A battery is not a flash light. The correct way to code this would be to give the flashlight a reference to its battery.

    From a practical standpoint you declare the same method (Start) in both classes. This is not allowed, without using the override or new keyword.

    If you just need an example of inheritance why not do it this way.
    • Battery
      • Lithium battery
      • Alkaline battery
    If on the other hand your teacher assigned the example to you... Well, lets just say you need a new teacher.

    And kill your statics too. You do not have permission to use static until you can tell me why static is a bad idea.