![](/img/trans.png)
[英]C# “An object reference is required for the non-static field,” Class issue with Static Member Function
[英]How do I reference a non-static member of a different class 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”需要對象引用。
我根本不了解如何從PlayerController.cs訪問BackgroundScroller.speed的值。 我不想創建對象引用,我只想簡單地更改其他類中的值。
干杯
路西歐
您不能靜態訪問speed
因為它不是靜態成員。 它是一個實例變量,只能通過實例化的BackgroundScroller進行訪問。
假設已經在某個位置調用了Start
並確保BackgroundScroller.current
不為null,則以下行將使您能夠訪問將當前靜態引用用於當前滾動器的速度。
BackgroundScroller.current.speed = setSpeed;
由於speed
不是靜態類型,因此可以通過在speed
變量中添加靜態來解決此問題。
嘗試將速度類型更改為static float
,例如
public static float speed;
然后您最終可以設置speed
值
void Setspeed(float setSpeed){
BackgroundScroller.speed = setSpeed;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.