[英]How do I reference a non-static member of a different class c#
I am trying to make a game where my background scrolls depending on how fast I want the player to be going. 我正在尝试制作一个游戏,其中我的背景会根据我希望玩家前进的速度而滚动。
I have tried creating a non-static function, that accesses BackgroundScroller.speed as a simple way to pass the value. 我尝试创建一个非静态函数,该函数将BackgroundScroller.speed作为传递值的一种简单方法。
. 。
(PlayerController.cs) (PlayerController.cs)
void Setspeed(float setSpeed){
BackgroundScroller.speed = setSpeed;
}
BackgroundScroller.cs looks like this: 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);
}
}
. 。
The error I get when I try and access BackgroundScroller.speed from PlayerController.cs is: "An object reference is required to access non-static member "BackgroundScroller.speed". 我尝试从PlayerController.cs访问BackgroundScroller.speed时遇到的错误是:“访问非静态成员“ BackgroundScroller.speed”需要对象引用。
I don't understand how to access the value of BackgroundScroller.speed from PlayerController.cs essentially. 我根本不了解如何从PlayerController.cs访问BackgroundScroller.speed的值。 I don't want to create an object reference, I just want to simply change the value in the other class.
我不想创建对象引用,我只想简单地更改其他类中的值。
Cheers 干杯
Lucio 路西欧
You cannot statically access speed
because it is not a static member. 您不能静态访问
speed
因为它不是静态成员。 It is an instance variable that can only be accessed through an instantiated BackgroundScroller. 它是一个实例变量,只能通过实例化的BackgroundScroller进行访问。
Assuming that Start
has already been called somewhere ensuring that BackgroundScroller.current
is not null, the following line will give you access to the speed to use the existing static reference for the current scroller. 假设已经在某个位置调用了
Start
并确保BackgroundScroller.current
不为null,则以下行将使您能够访问将当前静态引用用于当前滚动器的速度。
BackgroundScroller.current.speed = setSpeed;
Because the speed
is not static type and you can fix this by adding static in speed
variable. 由于
speed
不是静态类型,因此可以通过在speed
变量中添加静态来解决此问题。
Try to change your speed type to static float
, for example 尝试将速度类型更改为
static float
,例如
public static float speed;
then you can finally set the value of speed
然后您最终可以设置
speed
值
void Setspeed(float setSpeed){
BackgroundScroller.speed = setSpeed;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.