在Unity 2017.3中声明一个功能?

时间:2018-04-02 22:46:01

标签: c# unity3d

我正在学习使用Unity来完成我的功课,但是,当我尝试完成其中一个教程时,我遇到了一些我在教程中遇到的错误,这些错误似乎已经过时了。我的剧本是:

{

    public float speed;
    private Rigidbody rb;
    private int count; 
    public Text countText;

    void Start ()
    {
        rb = GetComponent<Rigidbody>();
        count = 0;
        SetCountText ();
    }

    void FixedUpdate ()
    {
        float moveHorizontal = Input.GetAxis ("Horizontal");
        float moveVertical = Input.GetAxis ("Vertical");

        Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);

         rb.AddForce (movement * speed); 
    }

    void OnTriggerEnter(Collider other) 
    {
        if (other.gameObject.CompareTag("Pickup"))
        {
            other.gameObject.SetActive(false);
            count = count + 1;
            SetCountText ();
        }

    void SetCountText ()
    {
        countText.text = "Count: " + count.ToString ();
        if (count >= 12)
        {
            winText.text = "You Win!";
        }
    }
}

我遇到的第一个错误是在&#34; void SetCountText()&#34;部分。编译器告诉我,void关键字不能在此上下文中使用。这是什么意思,我该如何解决?

我收到的下一个错误位于同一位置。为方便起见,我会将其粘贴在此处。 Assets / Scripts / PlayerController.cs(39,22):错误CS1525:意外符号(', expecting,&#39;,;', or =

我还收到了另一个错误,除了基本术语之外我无法解释,我无法解决。错误是

NullReferenceException: Object reference not set to an instance of an object
PlayerController.OnTriggerEnter (UnityEngine.Collider other) (at Assets/Scripts/PlayerController.cs:38)

我是否可以收到有关脚本如何出错的一些信息并修复这些错误?我知道所有Unity教程都使用&#34; void&#34;声明一个函数时的关键字,我可以请一些帮助吗?

总的来说,我希望了解出现了什么问题以及如何解决问题。

1 个答案:

答案 0 :(得分:3)

看起来您的代码中缺少一些部分。 就你的错误而言,你的 OnTriggerEnter()方法似乎缺少一个右括号} 。 尝试

{

public float speed;
private Rigidbody rb;
private int count; 
public Text countText;

void Start ()
{
    rb = GetComponent<Rigidbody>();
    count = 0;
    SetCountText ();
}

void FixedUpdate ()
{
    float moveHorizontal = Input.GetAxis ("Horizontal");
    float moveVertical = Input.GetAxis ("Vertical");

    Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);

     rb.AddForce (movement * speed); 
}

void OnTriggerEnter(Collider other) 
{
    if (other.gameObject.CompareTag("Pickup"))
    {
        other.gameObject.SetActive(false);
        count = count + 1;
        SetCountText ();
    }
}
void SetCountText ()
{
    countText.text = "Count: " + count.ToString ();
    if (count >= 12)
    {
        winText.text = "You Win!";
    }
}
}