[英]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. 现在在另一个gameObject中,我有另一个脚本,我想简单地调用函数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. 该错误发生在
begin
函数的第一行中。
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. 我是C#的新手,我最初学习过Javascript,所以我有点困惑如何引用该成员才能调用此函数。
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
类不是静态的,因此这实际上无法工作,您需要先像这样初始化它:
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. 并注意它们必须具有相同的名称空间,否则,您仍然需要在using指令中添加名称空间。
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");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.