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

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();

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.