Skip to content

Instantly share code, notes, and snippets.

@adampassey
Created July 13, 2014 22:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adampassey/ee77d324aa5af78e1717 to your computer and use it in GitHub Desktop.
Save adampassey/ee77d324aa5af78e1717 to your computer and use it in GitHub Desktop.
Polymorphism in Unity with C#
using UnityEngine;
using System.Collections;
public class Apple : Fruit
{
public void Start() {
weight = 0.5f;
}
}
using UnityEngine;
using System.Collections;
public abstract class Fruit : MonoBehaviour
{
public float weight = 0.2f;
public float Weight() {
return weight;
}
}
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