2014-11-25 38 views
0

我想製作一個遊戲,其中我的背景滾動取決於我希望玩家走多快。我如何參考不同類別的非靜態成員c#

我已經嘗試創建一個非靜態函數,它訪問BackgroundScroller.speed作爲傳遞值的簡單方法。

(PlayerController.cs)

void Setspeed(float setSpeed){ 

BackgroundScroller.speed = setSpeed; 

} 

BackgroundScroller.cs看起來是這樣的:

using UnityEngine; 
using System.Collections; 

public class BackgroundScroller : MonoBehaviour { 

public float speed = 0; 
public static BackgroundScroller current; 

float pos = 0; 

void Start() { 
    current = this; 
} 

public void Go() { 
    pos += speed; 
    if (pos > 1.0f) 
     pos-= 1.0f; 


    renderer.material.mainTextureOffset = new Vector2 (pos, 0); 
} 

} 

的錯誤,當我嘗試和PlayerController.cs訪問BackgroundScroller.speed是我得到:「對象引用才能訪問非靜態成員‘BackgroundScroller.speed’

我不明白怎麼訪問BackgroundScroller.speed從本質PlayerController.cs的價值。我不希望創建一個對象引用,我只是想簡單地在其他類更改值。

乾杯

盧西奧

回答

1

您不能靜態訪問speed,因爲它不是靜態成員。它是一個實例變量,只能通過實例化的BackgroundScroller訪問。

假設Start已在某處確保BackgroundScroller.current不爲空,下面的代碼行將使您能夠訪問使用當前滾動條的現有靜態參考的速度。

BackgroundScroller.current.speed = setSpeed; 
+0

完美的作品歡呼值。我也是一個白癡,我在之後的教程中使用了.current,它調用了go()。再次感謝。 – LucioMaximo 2014-11-25 06:01:57

1

因爲speed不是靜態類型,你可以通過在speed變量添加靜態解決這個問題。

試圖改變你的速度類型static float,例如

public static float speed; 

然後你終於可以設置speed

void Setspeed(float setSpeed){ 
    BackgroundScroller.speed = setSpeed; 
}