- Home /
Override a function?
Hello, is there a way to override a function in a script using another script (as in just canceling the first script's function)? Thanks
Answer by diabloroxx · Dec 04, 2010 at 12:52 AM
Can't you have a boolean variable attached in the first function and then make it false using the second function. Eg:
Script A -
bool AmActive = true;
void SomeFunction() { if(AmActive) .... blah blah blah }
Then in another script, you can make the bool AmActive as false.
Script B -
ScriptA.AmActive = false;
function SimilarFunction()
{
....
}
Of course you can use this to access other gameobjects. And the scripts using the GetComponent
Answer by _Petroz · Dec 04, 2010 at 09:59 AM
It's a strange approach to disable a single function in another script to override it. It might be a good place to utilize polymorphism.
If the function is going to be overridden for the whole lifetime of the object it is attached to then you could just use an abstract function with two different specializations. This is how you would do it in C#
base class:
abstract class Base : MonoBehaviour { abstract protected void foo();
// common functionality
}
specialization #1:
class FirstSpecialization : Base
{
override protected void foo()
{
// do stuff
}
}
specialization #2:
class SecondSpecialization : Base
{
override protected void foo()
{
// do other stuff
}
}
Answer by BerggreenDK · Dec 04, 2010 at 02:54 AM
I haven't testet it, but I fell quite sure that C# (and the other languages can do this).
here is how C# .NET does it. http://msdn.microsoft.com/en-us/library/ebca9ah3(VS.71).aspx
Same for C# MONO, I believe.
Answer by alienmax22 · Jan 21, 2015 at 02:49 PM
Maybe it's too late to answer, but you can use virtual directive
Base class
public class BaseClass : Monobehavior {
public virtual void MyFunction ()
{
Debug.Log("Base function run.");
}
}
Child class
public class ChildClass : BaseClass{
public override void MyFunction ()
{
// If you want to run base function as well use base
base.MyFunction();
Debug.Log("Child function run.");
}
}
Answer by Mike 12 · Dec 03, 2010 at 11:29 PM
No, not in Javascript. You can't, because Javascript doesn't have classes. However, you can override functions in C#. Just declare your function as either an abstract or virtual function. With abstract in C#, you only have to declare the function in the parent class. With virtual in C#, you have to implement the method in the parent class and the child classes can optionally override that function.
$$anonymous$$aybe should have put the "oop" or "inheritance" as a tag for your question so that more people could answer your question.
Sorry, but this is wrong. Javascript does have classes, and they work basically the same way as in C#.