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.
.
(PlayerController.cs)
void Setspeed(float setSpeed){
BackgroundScroller.speed = setSpeed;
}
BackgroundScroller.cs looks like this:
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".
I don't understand how to access the value of BackgroundScroller.speed from PlayerController.cs essentially. 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. It is an instance variable that can only be accessed through an instantiated 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.
BackgroundScroller.current.speed = setSpeed;
Because the speed
is not static type and you can fix this by adding static in speed
variable.
Try to change your speed type to static float
, for example
public static float speed;
then you can finally set the value of speed
void Setspeed(float setSpeed){
BackgroundScroller.speed = setSpeed;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.