- Home /
Can't Override Virtual Method In Inherited Class
I am currently on part 6 of the 2D Platformer Character Controller Live Session. I have a PhysicsObject class that inherits from MonoBehaviour, and a Player class that inherits from the PhysicsObject class, just like in the tutorial.
I have the following in PhysicsObject.cs:
void Update () {
targetVelocity = Vector2.zero;
ComputeVelocity();
}
protected virtual void ComputeVelocity()
{
}
and the following in my Player.cs:
protected override void ComputeVelocity()
{
// Handle horizontal movement
Vector2 move = Vector2.zero;
move.x = Input.GetAxis("Horizontal");
targetVelocity = move * maxSpeed;
// Handle jump
if (Input.GetButtonDown("Jump") && grounded)
{
velocity.y = jumpSpeed;
}
else if(Input.GetButtonUp("Jump"))
{
if (velocity.y > 0)
velocity.y *= .5f;
}
}
Player.cs's ComputeVelocity() should override PhysicsObject.cs's ComputeVelocity(), but this is not happening. ComputeVelocity() is being called by PhysicsObject, but it is the blank version in PhysicsObject.cs, not the overwritten version in Player.cs. I am able to use the function properly by calling it from Update() in Player.cs, but I cannot figure out why the override is not occurring.
Answer by Bunny83 · Jun 03, 2017 at 04:08 PM
I can guarantee that the code you provided does work, even without testing it. If it doesn't work for you, you probably have missed something about the setup. First make sure you only attach your Player script to your player object and not a "PhysicsObject" script.
I am able to use the function properly by calling it from Update() in Player.cs
So does that mean you implemented an Update method inside your Player script? In that case the Update in the base class will get hidden. A class can only have one Update method. If you want to make Update extendable in a child class it should be virtual in the base class and properly overridden in the child class. Also make sure you call base.Update()
inside your Player's Update if you want to keep that functionality.
Yep, this was the issue. I made both Update functions virtual and added base.Update()
to the Player's Update function so that both of them would be called (the physics are of course handled in PhysicsObject.cs while I have code for firing bullets in Player.cs's Update function). Thank you so much!
Thanks bunny, I was looking forever for an answer like this. I didn't realize the base class wasn't allowed to have a Start/Update function if the class I'm inheriting from already does.
Your answer
Follow this Question
Related Questions
Theory: Methods and Functions 1 Answer
Weird behaviour of an editor extension that sets variables on other scripts. 1 Answer
Animation Event (Function not supported) for a public overridden function 0 Answers
How do I override objects that aren't in the Hierarchy? 0 Answers
Is it worth making tons of similiar methods or create big one that connects things together? 2 Answers