簡體   English   中英

無法從C#中的另一個腳本調用方法? 使用Unity嗎?

[英]Cant call a method from another script in C#? Using Unity?

好吧,我在Unity3d論壇上四處打聽,沒有運氣。 我在這里嘗試一些非常簡單的操作,由於某種原因,我無法獲得一個C#腳本來調用另一個函數。

我在Unity中,我嘗試使用2個腳本來檢測GameObject上的簡單點擊並基於該點擊執行某些操作-OnMouseDown出於任何原因使我失敗。

我讀了一篇有關使用TouchManager腳本的文章,該腳本附加到空白處,以從被觸摸對象的腳本中調用函數,因此,這里是; 它使用Raycasts並應該獲取被觸摸的游戲對象,並稱為Touched()函數:

protected virtual void Update () {
    if (Input.touchCount > 1) {

        if (Input.touches [0].phase == TouchPhase.Stationary) {
            Ray ray = Camera.main.ScreenPointToRay (Input.touches [0].position);
            if (Physics.Raycast (ray, out hit, 100.0f)) {
                touchedObject = hit.transform.gameObject; 
                touchedObject.GetComponent<touchableGameObject> ().Touched ();
                print (touchedObject.name);
            } else print ("GetMouseButtonDown on nothing");
        }
    }
}

沒有第一個if,我在Array錯誤中得到了OutofBounds 但是現在,如果我沒有任何結果,那么請首先解決。

然后在我的敵人預制件(顯然是物體)上,我只有:

public void Touched() {
    print ("touched!! WORKING");
}

該函數是公共的,因此應該可以調用它。 我在Start()方法中有打印內容,因此我知道腳本可以正常工作,但是即使我清楚地觸摸/單擊游戲對象,也永遠不會調用Touched()方法。

如果在觸摸管理器腳本中沒有第一個if語句,那么在打印時我將始終獲得最后一個else:

print ("GetMouseButtonDown on nothing");

我對Unity和C#比較陌生,無法弄清楚。 我需要這個來工作,我很絕望。

一個人如何基於來自另一個C#腳本的觸摸來調用函數?

這是一個非常簡單的錯誤。

一觸時, Input.touchCount1 當有2Input.touchCount值為2。

您的代碼存在以下問題if (Input.touchCount > 1) {

僅在檢查觸摸是否大於1

您應該檢查touch if (Input.touchCount >= 1)或等於1if (Input.touchCount >= 1)

要么

如果touch大於0if (Input.touchCount > 0)

任何一種都可以解決您的問題。

最后,不能保證被觸摸的GameObject會附加上touchableGameObject腳本。 因此,在調用其Touched()函數之前,必須檢查GetComponent<touchableGameObject>()是否為null 請大寫腳本名稱。 這將使您更容易識別腳本和變量名。

protected virtual void Update()
{
    if (Input.touchCount >= 1)
    {
        if (Input.touches[0].phase == TouchPhase.Stationary)
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.touches[0].position);
            if (Physics.Raycast(ray, out hit, 100.0f))
            {
                touchedObject = hit.transform.gameObject;


                touchableGameObject touchScript = touchedObject.GetComponent<touchableGameObject>();
                if (touchScript != null)
                {
                    touchScript.Touched();
                }

                print(touchedObject.name);
            }
            else
            {
                print("GetMouseButtonDown on nothing");
            }
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM