2015-06-25 36 views
0

我想一些UnityScript代碼轉換爲d#和我收到以下錯誤:錯誤的UnityScript轉換爲C#

Expression denotes a method group, where a variable , value or type was expected on the Getcomponent

void Update() 
{ 
    float xVel = GetComponent().Rigidbody2D().velocity.x; 
    if(xVel < 18 && xVel > -18 && xVel !=0){ 
     if(xVel > 0){ 
      GetComponent.Rigidbody2D().velocity.x=20; 

     }else{ 
      GetComponent.Rigidbody2D().velocity.x = -20; 

     } 
    } 
} 
+0

你試着實際分配'xVel'嗎? –

+0

向我們展示GetComponent的代碼。 –

+0

Getomponet是統一的內置方法http://docs.unity3d.com/ScriptReference/Component.GetComponent.html – Student

回答

5

您的問題是:GetComponent().Rigidbody2D()因爲那是你沒怎麼使用GetComponent,你看到的錯誤可能是因爲GetComponent需要一個參數或指定的類型。 JS和C#的GetComponent有點不同。你可能的意思是:

void Update() 
{ 
    float xVel = GetComponent<Rigidbody2D>().velocity.x; 
    if(xVel < 18 && xVel > -18 && xVel !=0){ 
     if(xVel > 0){ 
      GetComponent<Rigidbody2D>().velocity.x = 20; 

     }else{ 
      GetComponent<Rigidbody2D>().velocity.x = -20; 

     } 
    } 
} 

也在C#中,我不認爲你可以直接修改速度,由於它周圍的屬性包裝。相反,您必須手動將速度更新爲新的Vector2。如果您只想設置x值,請傳入現有的y值。

我會寫它是這樣的:

private Rigidbody2D _rigidBody; 

void Start() 
{ 
    _rigidBody = GetComponent<Rigidbody2D>(); 
} 

void Update() 
{ 
    float xVel = _rigidBody.velocity.x; 
    if(xVel < 18 && xVel > -18 && xVel !=0){ 
     if(xVel > 0){ 
      _rigidBody.velocity = new Vector2(20, _rigidBody.velocity.y); 

     }else{ 
      _rigidBody.velocity = new Vector2(-20, _rigidBody.velocity.y); 
     } 
    } 
} 

雖然我會改變那魔法18中的變量太多,但我不能讓一個猜測,此間究竟意味着什麼!

+0

它仍然給我這個錯誤:無法修改'UnityEngine.Rigidbody2D.velocity'的值類型返回值。考慮將該值存儲在一個臨時變量中 – Student

+3

我認爲速度不能手動修改。你需要這樣做:'_rigidBody.velocity = new Vector2(newXHere,_rigidBody.velocity.y);' – mGuv

+0

抱歉打擾你,但你真的很有幫助我得到一個有關此代碼的錯誤_rigidBody.velocity = new Vector2( y/2,_rigidBody.velocity.x)+ colInfo.collider.GetComponent ().velocity.y/3; 它的說法'UnityEngine.Vector2.Vector2(float,float)'的最佳重載方法匹配有一些無效參數,參數'#1'不能將'object'表達式轉換爲'float'類型 – Student

2
float xVel = GetComponent<Rigidbody2D>().velocity.x; 

GetComponent是這樣使用的。