Calling methods on inherited classes in C#

Hey all, I’m still trying to wrap my brain around polymorphism, inheritance, and all this OOP nonsense. I come from a procedural scripting background so my gut instincts are all wrong when trying to do some actual programming.

The framework I’m attempting is sort of a hierarchy. The Entity class is like the nervous system, and gives the other components easy access to each other, as well as telling the components when to act so I can control the order in which things happen. There’s Movement and Brain (controls for the player, AI for enemies) base classes, and inherited classes created (Move_Human, Brain_Player) under those.

My Entity class has no subclasses, and it’s variables are typed as the Base classes for movement and brain. When the entity calls a method from an attached Move_Human component, The Movement script is what actually runs it’s method.

How the heck do I run the inherited methods rather than the base methods?

The example code below prints out “Movement says HI!”. There’s a single game object with an Entity and a Move_Human component applied.


public class Entity : MonoBehaviour {
	
	public Movement myMove;
	
	// Use this for initialization
	void Start () {
		myMove = gameObject.GetComponent<Movement>();
		myMove.sayHi();
	
	}

}

public class Movement : MonoBehaviour {

	public void sayHi(){
	     Debug.Log("Movement says HI!");	
	}

}

public class Move_Human : Movement {
	
	void sayHi(){
	     Debug.Log("Move_Human says HI!");	
	}

}

Also, can anyone recommend resources to untrain my brain of it’s procedural ways?

Thanks -

Chris Luckenbach

Get familiar with the ‘virtual’ keyword: virtual - C# Reference | Microsoft Learn

Basically, your base class declares a method as virtual, then calling it will call the derived method instead. Basically.

Well you should define SayHigh as virtual and then use override keyword in Move_human.

Some points, For keeping with standards use caps letters instead of underscores (_). soe MoveHuman instead of Move_human
It’s better to name it HumanMovement however.

I recommend the book code complete for general great guidelines about coding and for learning object oriented C# programming i recommend C# how to program if you are a beginner and programming C# by j.liberty if you are advanced (which it doesn’t seem and you say you are comming from a procedural background)