new to C# but JS experienced... have a C# ?

Hey all, I have a quick and easy C# question for you.

How would I go about using the child method?

I have a parent class, and a child class as follows:

If I attach the script to a GameObject, I can obviously use, “gameObject.GetComponent().AddToCurrentHP()”. Is there a trick to use the child instead?

using UnityEngine;
using System.Collections;

public class VitalController : MonoBehaviour {
	
	void Start () {
	
	}

	void Update () {
	
	}

	public float AddToCurrentHP(float currentHP, float howMuch) {
		Debug.Log("Using parent method");
		return currentHP + howMuch;
	}
}

public class PlayerVitals : VitalController {
	
	public float AddToCurrentHP(float currentHP, float howMuch) {
		Debug.Log("Using child method");
		return currentHP + howMuch;
	}
}

You mean PlayerVitals is attached to the GameObject but you’re using VitalController in the GetComponent call?

If so - make VitalController:AddToCurrentHP virtual and override it in PlayerVitals. As you have it now you should be getting compiler warnings about hiding.

the PlayerVitals class is just a child class of the class VitalController, so they both reside in the same .cs file.

The component attached to the GameObject is VitalController (which has the definitions of both the parent and child classes).

Edit:

I was just slightly confused on how to format child classes. To fix:

Put the child class definition into a separate class file.
Add the child class onto the game object, and removed the parent class.
The GameObject now was the ability to call the attached child methods, as well as the inherited parent methods.

gameObject.GetComponent().methodName();

Thanks for the help mate.

It’s called overriding.

public class Parent
{
    public virtual void Method()
    {
        // Some logic
    }
}

public class Child
{
    // This class is always call first.
    public override void Method()
    {
        // Some logic
        base.Method(); // Use to call the implementation in Parent
    }
}

Which will give;

Parent parent = new Child();
parent.Method(); // Calls the current type implementation, which is Child.

If you don’t do the overriding, the method called will be the implementation of the current variable type.

Parent parent = new Child();
parent.Method(); // calling the parent version.

Child child = new Child();
child.Method(); // calling the child version.

However, if the second behaviour is wanted - sometimes - the keyword “new” is there to be clear that your goal is to hide the parent’s implementation.