从C#unity3D

时间:2016-04-04 02:29:38

标签: c#

我有一个带有公共函数的脚本,它设置了这样的动画触发器:

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,所以我有点困惑,我会如何引用该成员来调用此函数。

希望你能提供帮助。

2 个答案:

答案 0 :(得分:2)

由于您的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
   }
 }

答案 1 :(得分:1)

基本上你可以使用静态辅助类来为动画师设置东西:

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");
    }
}