Created
July 13, 2014 22:37
-
-
Save adampassey/ee77d324aa5af78e1717 to your computer and use it in GitHub Desktop.
Polymorphism in Unity with C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
public class Apple : Fruit | |
{ | |
public void Start() { | |
weight = 0.5f; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
public abstract class Fruit : MonoBehaviour | |
{ | |
public float weight = 0.2f; | |
public float Weight() { | |
return weight; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
/** | |
* Create an empty GameObject in the scene | |
* and attach the Apple component and this Usage | |
* component. | |
* | |
* Pressing 'B' will return the proper result | |
* of the Apple component (0.5f), not the | |
* Fruit base class- despite the retrieval of the | |
* component using `<Fruit>` | |
* | |
**/ | |
public class Usage : MonoBehaviour | |
{ | |
private Fruit fruit; | |
public void Start() { | |
fruit = gameObject.GetComponent<Fruit>(); | |
} | |
public void Update() { | |
if (Input.GetKeyDown(KeyCode.B)) { | |
fruit = gameObject.GetComponent<Fruit>(); | |
Debug.Log(fruit.Weight()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment