c# - 将代码行作为参数传递给函数

标签 c# unity3d

我希望将一行代码传递到我在 c# 中调用的函数中,目的是优化我的代码并尝试学习新的东西。正如我在代码中所示,我熟悉使用字符串、整数、 float 和 bool 值。

想法是在单击按钮时调用一个函数来停止脚本并再次开始脚本。没有该功能,此代码可以正常工作:

public void PlayOnClick()
{
    if(count != 1)
    {
        m_animator.GetComponent<Animator>().Play("Scale");
        d_animator.GetComponent<Animator>().Play("CloseUp");
        ((MovieTexture)MovieOne.GetComponent<Renderer>().material.mainTexture).Play();
        Dialyser.GetComponent<RotationByMouseDrag>().enabled = false;
        count = 1;
    }
    else
    {
        m_animator.GetComponent<Animator>().Play("Scale");
        d_animator.GetComponent<Animator>().Play("ScaleDown");
        ((MovieTexture)MovieOne.GetComponent<Renderer>().material.mainTexture).Stop();
        Dialyser.GetComponent<RotationByMouseDrag>().enabled = true;
        count = 0;
    }     
}

不过我相信这可以缩短。到目前为止我已经得到了这个:

void Lock(string A, string B, ? C, bool D, int E)
{
    m_animator.GetComponent<Animator>().Play(A);
    d_animator.GetComponent<Animator>().Play(B);
    C;
    Dialyser.GetComponent<RotationByMouseDrag>().enabled = D;
    count = E;

}

在函数 C 中,我想在按下一次时传递以下行:

((MovieTexture)MovieOne.GetComponent<Renderer>().material.mainTexture).Stop();

再次按下时将其更改为:

((MovieTexture)MovieOne.GetComponent<Renderer>().material.mainTexture).Play();

我遇到过 eval - 但我相信这仅适用于 javascript,并且可能会占用大量处理器资源。我研究过将该行解析为字符串。

我目前在搜索和尝试方面都胜出。任何人都可以为我阐明这一点吗?

最佳答案

您正在寻找的是委托(delegate),或者用 C++ 术语来说是函数指针。

您可以在 delegates 上找到更多信息这里。

Actions可能感觉用它编码更快。

基本上,您可以传递对要执行的方法的引用。方法的签名应与方法中声明的参数类型完全相同。因此,如果您希望传递并运行一段不返回任何值的代码,您可以使用不带任何类型参数的 Action 类型。例如

class A {
    void printAndExecute(String textToPrint, Action voidMethodToExecute) {
        Debug.Log(textToPrint);
        voidMethodToExecute();
    }
}

class B : MonoBehaviour {
    void Start() {
        new A().printAndExecute("SAY", sayHello);
    }

    void sayHello() {
        Debug.Log("Hello!");
    }
}

希望对你有帮助

关于c# - 将代码行作为参数传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43999429/

相关文章:

c# - 如何在场景之间保持值(value)?

c# - sgen.exe x64 .net c# 失败,出现 "assembly with an incorrect format"

c# - for 循环中的集合值更改

c# - 如何从 p12 文件中读取 SecretKey?

c# - 找不到命名空间或数据类型 NavMeshAgent Unity 3d

c# - 代码剥离错误 Unity

c# - 契约(Contract) - 如何要求集合不包含空值

C#:如何解析用户查询

c# - 在 Unity 中预处理音频频谱数据

unity3d - unity 刚体恒速