2016-06-12 37 views
0

所以不得不在统一的一个基本问题:统一C#如何使一个变量等于另一个不使用静态关键字

public int A = 0; 
int B = A; 

此代码抛出“A字段初始不能引用非静态字段,方法或属性'错误。

所以我能做到这一点:

public static int A = 0; 
int B = A; 

其中一期工程,但后来变量“A”不会对检查显示。我可以吃我的蛋糕,也可以吃,它有一个可以相等的变量,并让它出现在检查员身上?谢谢。这可能已经在C#工作

+1

静态方法不能访问非静态字段,如果你想有一个是非静态的,然后使用也必须是非静态方法,类也不能是静态的。你需要发布完整的源代码给其他人建议更改。 –

+0

@Rosdi Kasim这个类不是静态的。 – Demandooda

+0

David是对的,你不能在'start'或'awake'之前将var的值赋给var,你需要'start'来初始化 – tim

回答

2
public int A = 0; 
public int B; 

void Start() { 
    B = A; 
} 
0

解决方案:

public const int A = 9; 
int B = A; 

而且

public static int A = 9; 
int B = A; 

Staticconstant变量不能显示在Unity编辑器。如果你想分配AB,并且仍然让它在编辑器中显示,你必须在一个函数中做到这一点。

如果你想总是有-相同的值一个 throuout程序运行时,

public int A; 
int B; 

//Initialize A to B 
void Start() 
{ 
    B = A; 
} 

//Make B always equals to A 
void Update() 
{ 
    B = A; 
} 
0

因为类是不固定的,你的域不会被初始化,直到你真正建立例如,该类的一个实例。

public class Bot 
{ 
    public int a = 0; 
    public int b; 
    //If you try this it will not work 
    //public int b = a; 

    public Bot() 
    { 
     //This will work because once you create Bot, all fields will be initialized 
     this.b = a; 
    } 
} 

public static void Main() 
{ 
    //Once you create the class the Bot constructor will be called automatially 
    Bot botty1 = new Bot(); 
} 
相关问题