- Home /
c# - copy a function in another?
Hi all,
Beeing new to programming, this question might be stupid... Sorry if it is.
I wanted to know if (and how) it would be possible to copy a function script to another one.
example of what I would like to do:
in script 'Attacks':
void attack1()
{
}
void attack2()
{
}
void OnGUI()
{
if (GUI.button(new Rect(0,0,100,100),"att01"))
{
attack1() = gameObject.GetComponent<Warrior>().att01();
}
}
the function 'att01()' would thus be included in the script 'Warrior' attached to the same GameObject.
Is something like this possible? How?
Thanks for your help
Answer by GameVortex · Jan 06, 2014 at 01:46 PM
You can sort of do that with events and delegates. Something like this:
private delegate void CopiedFunction();
private CopiedFunction copiedFunction;
private void Start()
{
copiedFunction = FunctionToCopy;
//using the function:
copiedFunction();
}
private void FunctionToCopy()
{
}
Keep in mind that the function to copy needs to match the signature of the delegate (the return value and the parameters needs to be the same).
**Here** you can read more about the use of delegates.
Perfect thanks, it works (of course ;) ) simple & verry usefull to me
Answer by Bunny83 · Jan 06, 2014 at 01:44 PM
You can't "copy" a function. C# is not a dynamic scripting language. Every function / method is compiled. However what you want is called a delegate. A delegate is like a "function pointer". It allows you to assign a function with the same signature to a delegate variable. Then you can use the variable to execute the assigned function:
You can define a delegate type like this:
public delegate RETURNTYPE MyDelegateType(PARAMETERS);
There is a predefined type "Action" which equals:
public delegate void Action();
To define a delegate variable you simply use the delegate as type:
public MyDelegateType variableName;
So in your case you can do:
public System.Action attack1;
void OnGUI()
{
if (GUI.button(new Rect(0,0,100,100),"att01"))
{
attack1 = gameObject.GetComponent<Warrior>().att01;
}
}
If you want to execute the delegate just do this:
attack1();
great thanks, i'll try this this evening. Is this a heavy from a ressource point of view?
Thanks, I just had to declare it as GameVortex wrote bellow, I probably miss typed something as with yours I was not able to declare the 'att01'
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Getting a Non Static Variable From a Different C# Script 2 Answers
Algorithm for loading sounds 1 Answer