简体   繁体   中英

Call a function from other script in C# unity3D

I have a script with a public function which sets up an animation trigger like this:

public class AnimationManager : MonoBehaviour {

    public Animator menuAnim;

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

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

Now in a different gameObject i have another script that i want to simply call the function Test. So i made a script that did this:

public class Testing : MonoBehaviour {

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

But this leads to this error:

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

The error occurs in the first line of the begin function.

I am new ish to C# i originally learnt Javascript, so i am a bit confused how i would reference the member in order to call this function.

Hope you can help.

This won't really work since your AnimationManager class isn't static, you need to initialize it first like this:

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

And take note they must have the same namespace, if not, you still need to add the namespace in the using directive.

Edited:

public static class AnimationManager : MonoBehaviour {

    public Animator menuAnim;

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

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

This is how you're gonna call it:

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
   }
 }

Basically you could use a static helper class to set things for the animator:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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