I’m very new to programming and i’m going through the unity scripting tutorials and I’m currently messing around with concept of polymorphism and overriding. I have 2 scripts.
parent script :
using UnityEngine;
using System.Collections;
public class Animal : MonoBehaviour
{
void Start()
{
Yell();
}
public virtual void Yell()
{
Debug.Log ("This is the Animal Class!");
}
}
and my child script thats being attached to an object.
using UnityEngine;
using System.Collections;
public class Lizard : Animal
{
Animal newLizard = new Lizard();
void Start ()
{
newLizard.Yell();
// base.Yell();
}
public override void Yell()
{
Debug.Log("This is a Lizard Class");
}
}
When I add newLizard.Yell(); and save the script and switch over to unity, it crashes. Can someone tell me what I’m doing wrong.
Hey Suddoha. I’m not following. I was trying to upcast the Lizard child class to Animal parent class(on line 6) and on line 10 my intention was to run the Yell function in the Animal class. Let me know if you understand. Thanks in advance.
using UnityEngine;
using System.Collections;
public class Lizard : Animal
{
//
// CAN'T DO THIS: Animal and Lizard are MonoBehaviour and as such must
// be instantiated with AddComponent like shown in Awake.
//
// Animal newLizard = new Lizard();
Animal newLizard;
//
// Awake is always called before start - never assume any other objects exists yet though.
//
void Awake ()
{
newLizard = this.gameObject.AddComponent<Lizard>();
}
void Start ()
{
newLizard.Yell();
// base.Yell();
}
public override void Yell()
{
Debug.Log("This is a Lizard Class");
}
}