unity报错【5】【CS0236】 A field initializer cannot reference the non-static field, method, or property

public class QuaternionExample : MonoBehaviour
{
    
    
    float rotX = transform.eulerAngles.x;

    void Start()
    {
    
    
        if (rotX > 180) 
        {
    
    
            rotX = rotX - 360f; 
        }
        print(rotX);
    }


    void Update()
    {
    
        
    }
}

【报错】error CS0236: A field initializer cannot reference the non-static field, method, or property ‘Component.transform’
成员字段(类级变量)不能引用非静态字段/方法/属性。为什么在方法下面能引用,不还是A field initializer?

解决

float rotX = transform.eulerAngles.x;

改成

public class QuaternionExample : MonoBehaviour
{
    
    
    float rotX;

    void Start()
    {
    
    
        rotX = transform.eulerAngles.x;
        if (rotX > 180) 
        {
    
    
            rotX = rotX - 360f; 
        }
        print(rotX);
    }

参考:https://support.unity.com/hc/en-us/articles/206829863-What-is-CS0236-

猜你喜欢

转载自blog.csdn.net/qq_50653422/article/details/129711443