繁体   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