繁体   English   中英

从C#unity3D中的其他脚本调用函数

[英]Call a function from other script in C# unity3D

我有一个带有公共功能的脚本,该脚本设置了如下的动画触发器:

public class AnimationManager : MonoBehaviour {

    public Animator menuAnim;

    void Start () {
        menuAnim = GetComponent<Animator>();
    }

    public void Test() {
        menuAnim.SetTrigger("Fade");
    }
}

现在在另一个gameObject中,我有另一个脚本,我想简单地调用函数Test。 所以我做了一个脚本来做到这一点:

public class Testing : MonoBehaviour {

   void begin(){
     AnimationManager.Test();
   // other stuff
   }
 }

但这导致此错误:

 An object reference is required to access non-static member `AnimationManager.Test()'

该错误发生在begin函数的第一行中。

我是C#的新手,我最初学习过Javascript,所以我有点困惑如何引用该成员才能调用此函数。

希望能对您有所帮助。

由于您的AnimationManager类不是静态的,因此这实际上无法工作,您需要先像这样初始化它:

AnimationManager someName = new AnimationManager();
someName.Test();

并注意它们必须具有相同的名称空间,否则,您仍然需要在using指令中添加名称空间。

编辑:

public static class AnimationManager : MonoBehaviour {

    public Animator menuAnim;

    static void Start () {
        menuAnim = GetComponent<Animator>();
    }

    public static void Test() {
        menuAnim.SetTrigger("Fade");
    }
}

这就是您的称呼方式:

public class Testing : MonoBehaviour {

   void begin(){
     AnimationManager.Test(); //since your AnimationManager class is already static
//you don't need to instantiate it, just simply call it this way
   // other stuff
   }
 }

基本上,您可以使用静态帮助器类为动画师设置内容:

public class AnimationManager : MonoBehaviour {

    public Animator menuAnim;

    void Start () 
    {
            menuAnim = GetComponent<Animator>();
    }

    public void Test() 
    {
        AnimationHelper.Test(menuAnim);
    }
}

public class Testing : MonoBehaviour 
{
   void begin()
   {
    Animator menuAnim = GetComponent<Animator>();
    AnimationHelper.Test(menuAnim);
   }
}

public static AnimationHelper
{
    public static void Test(Anímation animation)
    {
        animation.SetTrigger("Fade");
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM