- Home /
Too subjective and argumentative
How do I call function in inhereted script?
Kind of like how Unity calls Awake() in a script inheriting from MonoBehaviour, I want to call Initialize() and Execute() in any scripts inheriting from Ability.cs. How can I do this in C#?
Answer by CorruptedTNC · Mar 27, 2015 at 12:56 PM
The function you're looking to call in the parent script must be public, then just call it as you would any other function.
using UnityEngine;
using System.Collections;
public class Parent : MonoBehaviour
{
public void ParentFunction()
{
Debug.Log("Parent function was called!");
}
}
using UnityEngine;
using System.Collections;
public class Child : Parent
{
// Use this for initialization
void Start ()
{
ParentFunction();
}
}
um, the commenter above answered your question - his answer contains 2 scripts, Parent and Child.
Although I'd like to amend his answer - the function you're calling in the parent script doesn't have to be public
, it can also be protected
if you're only calling it from a child class.
Or, if you mean 'how do I call function Foo(), implemented in Parent, when I have a reference to Child, and want to call it from Other?
Then you can do
public class Other : $$anonymous$$onoBehaviour {
public Parent parent;
public Child child;
void Call(){
//both of these methods work!
parent.Foo();
child.Foo();
}
}
If you want to call a method Bar() that is only implemented in Child, though, it gets a little trickier.
You can either do something like
Child c = parent as Child;
if(c) c.Bar();
Or you could make an abstract Bar() method in Parent.
I'm confused. I don't know if the child has Foo(), only that the parent has Foo(). Basically, I want to have a moddable ability system for each player that I can drag and drop certain scripts onto. Each ability will inherit from the class 'Ability' and will have the function Execute(). I don't know that the child will be called Child; it could be called FireBall, $$anonymous$$agic$$anonymous$$issile, etc. but the main thing is it has the function Execute() and I need to call Execute() from the Game$$anonymous$$anager; not from the child or whatever. It's okay; I actually got the answer here: http://gamedev.stackexchange.com/questions/97358/callback-on-derived-class.
Follow this Question
Related Questions
An OS design issue: File types associated with their appropriate programs 1 Answer
Distribute terrain in zones 3 Answers
Is it possible to make sealed overridden MonoBehaviour method. 0 Answers
C# Inheriting from MonoBehaviour but still be able to instantiate with new()? How should I do this? 2 Answers
How to call a function on all scripts which are derived from monobehaviour on awake and ondisable? 1 Answer