Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/visual-studio/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Unity C如何在另一个脚本中引用下标?_C#_Visual Studio_Unity3d - Fatal编程技术网

C# Unity C如何在另一个脚本中引用下标?

C# Unity C如何在另一个脚本中引用下标?,c#,visual-studio,unity3d,C#,Visual Studio,Unity3d,在以下脚本中,由于保护级别的原因,我得到了无法访问的错误: public class WrongAnswerScript : MonoBehaviour { void OnMouseDown() { GetComponent<Renderer>().material.color = Color.red; GameManager.UpdateMistakes(1); } } 以下是管理更新的GameManager类的代码: pu

在以下脚本中,由于保护级别的原因,我得到了无法访问的错误:

public class WrongAnswerScript : MonoBehaviour
{
    void OnMouseDown()
    {
        GetComponent<Renderer>().material.color = Color.red;
        GameManager.UpdateMistakes(1);
    }
}
以下是管理更新的GameManager类的代码:

public class GameManager : MonoBehaviour
{
    public List<GameObject> targets;
    public TextMeshProUGUI mistakeText;
    public int mistakes;

    void Start()
    {    
            mistakes = 0;
            mistakeText.text = "Mistakes: " + mistakes;
    }

    // Update is called once per frame
    void UpdateMistakes(int mistakesToAdd)
    {
        mistakes += mistakesToAdd;
        mistakeText.text = "Mistakes: " + mistakes;
    }
}

如何正确启动脚本?我是C语言的新手,所以我很难理解它的基本原理。

将函数公开,以便可以访问

public void UpdateMistakes(int mistakesToAdd)
您可能需要确保引用场景中某个地方现有的GameManager实例

private bool HasBeenClicked = false;
void OnMouseDown()
{
    GetComponent<Renderer>().material.color = Color.red;
    //Only do this block when you have not clicked before
    if (!HasBeenClicked)
    {
        //get a reference to the gamemanager that is already somewhere in the scene
        GameManager gameManager = (GameManager)FindObjectOfType(typeof(GameManager));
        gameManager.UpdateMistakes(1);
        HasBeenClicked = true;
    }
}

公共和静态,如果他们想通过GameManager.UpdateMistakes1访问;我希望这是一个单例,看看公共int错误不是静态的。我在第二个脚本中收到了一些错误。typeOf在当前上下文中不存在,GameManager是一种在给定上下文中无效的类型。我在那里输入了一个打字错误,其中typeOf都是小写。我在答案中调整了它。这应该可以解决这两个问题。如果不是的话,我会尽量留意这里的评论谢谢你,我现在已经开始工作了,但是我想知道如何使一个数字只能增加一次而不是无限大?这可能吗?