2014-11-25 57 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; 
}