Inheritance


As an OOP, you can use inheritance in your projects. This provides easy coding for you. For example, if you will create some of characters in your project, you can create a character class and use it for all different characters.

Lets create a character class.

using UnityEngine;
using System.Collections;

public class Character
{
	public string charType;

	public Character(){
		charType = "Mage";
	}

	public Character(string newType){
		charType = newType;
	}

	public void Shout(){
		Debug.Log ("I'm a " + charType);
	}
}

This class includes a character type and a function named Shout. Now create a Soldier class.

using UnityEngine;
using System.Collections;

public class Soldier : Character
{
	public Soldier(){
		charType = "Warrior";
	}

	public Soldier(string newType) : base(newType){
		Debug.Log ("Create a soldier");
	}
}

This script uses the public specifications of Character class with inheritance. Lets use these two scripts in another.

using UnityEngine;
using System.Collections;

public class Game : MonoBehaviour
{
	void Start(){
		Character character = new Character ();
		Soldier soldier = new Soldier ();
		soldier.Shout ();

		soldier = new Soldier ("Paladin");
		soldier.Shout ();
	}
}

This script creates new character of Character and soldier of Soldier. We set a new type of soldier.

©Coffee Break Codes – Inheritance

Leave a comment

Your email address will not be published. Required fields are marked *