Axelmov74
Axelmov74

Reputation: 33

Cast child script to parent script and keep child script behavior - Unity

I have a problem with some scripts.

The parent script :

ParentScript : MonoBehavior {
   public void test() {
     // DoSomething
   }
}

the child script :

ChildScript : ParentScript {
   public void test() {
     // DoSomethingSpecific
   }
}

The child script is assigned to a specific weapon prefab and the parent script on other more basic weapon. Weapons prefabs are stocked in a list of GameObject and, for each weapon, i want to get the script and execute the test method. Here is what i tried for each weapon :

currentWeapon.GetComponent<ParentScript>().test();

But, unfortunately, only the parent script test function is called and the child script test function is not called for the specific weapon.

Do you have a better solution to manage this ?

Upvotes: 0

Views: 740

Answers (1)

MatthieuL
MatthieuL

Reputation: 524

The parent's method should be marked as "virtual" to be overriden in child. And in the child method, you need to mark it "override" like this :

public class TestParent : MonoBehaviour
{
    virtual public void Test()
    {
        Debug.Log("InParent");
    }
}

public class TestChild : TestParent
{
    public override void Test()
    {
        Debug.Log("InChild");
    }
}

GetComponent<TestParent>().Test(); // show "inChild" if the component if a TestChild instance.

"The virtual keyword is used to modify a method, property, indexer, or event declaration and allow for it to be overridden in a derived class. "

"The override modifier is required to extend or modify the abstract or virtual implementation of an inherited method, property, indexer, or event."

ref : https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/override https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/virtual

Upvotes: 2

Related Questions