簡體   English   中英

C#和Unity出現使我感到困惑的錯誤

[英]C# and Unity getting errors that confuse me

我對此是全新的,並且對所輸入的代碼有一些難題。我遵循了教程,但仍然遇到一些問題。 我想要做的就是移動附着了此腳本的對象Player,該腳本是PlayerMovement。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour {

    public object Player(PlayerMovement) { // Identifier expected, and 'PlayerMovement.Player(PlayerMovement)' not all codes return a value
    {
        if (Input.GetKeyDown(KeyCode.W))
        {
            Transform.Translate(Vector3.forward * Time.deltaTime);  //ERROR: An object reference is required for the non-static field, method or property 'Transform.Translate(vector3)

            Debug.Log("W is pressed, and I should move forwards.");
        }

        if (Input.GetKeyDown(KeyCode.S))
        {
            Debug.Log("S is pressed, and I should move backwards.");
        }

        if (Input.GetKeyDown(KeyCode.A))
        {
            Debug.Log("A is pressed, and I should move left.");
        }

        if (Input.GetKeyDown(KeyCode.D))
        {
            Debug.Log("D is pressed, and I should move right.");
        }
    }
}

在第22行,我收到2個Identefier預期的錯誤,並且'PlayerMovement.Player(PlayerMovement)'並非所有代碼都返回一個值。

在第29行上,我得到非靜態字段,方法或屬性'Transform.Translate(vector3)'的對象引用是必需的

由於我是嶄新的,我一直在尋找答案,而且每個小時都在搜索,每當我在google上搜索到的任何內容都不能真正解釋我在做什么的時候,或者只是閱讀得不正確。

第22行的錯誤是由於Player函數的類型為object而導致的,您沒有在該方法中返回任何對象。 如果您更換:

public object Player(PlayerMovement)

與:

public void Player(PlayerMovement)  

該錯誤應該消失,或者您可以返回一個對象,但是我不確定那會是什么。

首先,如精神鯉魚所說。 程序將期望返回值,因此您應該返回一個值或將對象更改為void

public object Player....

變成一個

public void Player....

然后主要的問題是您正在調用Transform.Translate而不是更改gameObject的實際變換。 就像您說的那樣,PlayerMovement腳本已附加在您的玩家游戲對象上,因此目標是使游戲對象發生變化,其變換取決於按鍵輸入。 嘗試調用轉換本身而不是轉換類。 transform是游戲對象的實際轉換,而Transform是類,因此您在調用靜態方法,請嘗試使用this.transform.Translate

this.transform.Translate(Vector3.forward * Time.deltaTime);

然后最后一件事,請確保在Update方法中調用您的方法以使其起作用

暫無
暫無

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

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