簡體   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