我在Unity中收到2条错误消息,无法解决该问题

时间:2019-12-07 09:21:50

标签: c# unity3d

我收到2条错误消息,无法找出解决方法。

Assets\Scripts\you.cs(14,62): error CS0236: A field initializer cannot reference the non-static field, method, or property 'you.speed'

Assets\Scripts\you.cs(25,58): error CS1061: 'GameObject' does not contain a definition for 'position' and no accessible extension method 'position' accepting a first argument of type 'GameObject' could be found (are you missing a using directive or an assembly reference?)

也许有人可以帮助我吗? 角色在撞到地面之前只能跳一次,否则它会飞走。 我在引擎上附加了一个地面检查对象,但我不断收到这些错误。

using UnityEngine;
using System.Collections;

public class you : MonoBehaviour
{
    public float upForce = 100f;
    public LayerMask ground;
    private Rigidbody2D rb2d;
    public float speed = 20f;
    public bool isgrounded = true;
    public float checkradius = 0.5f;
    public GameObject groundcheck;
    public float translation = Input.GetAxis("Horizontal") * speed;

    void Start()
    {
        rb2d = GetComponent<Rigidbody2D>();
    }

    void Update()
    {

        transform.Translate(translation, 0, 0);
        isgrounded = Physics2D.OverlapCircle(groundcheck.position, checkradius, ground);


        if (isDead == false)
        {
            if (Input.GetKeyDown("space"))
            {
                rb2d.velocity = Vector2.zero;
                rb2d.AddForce(new Vector2(0, upForce));
            }
        }
    }
}

2 个答案:

答案 0 :(得分:1)

    public float translation = Input.GetAxis("Horizontal") * speed;

不能为字段,因为速度不是静态字段。将其更改为静态/ const,它应该可以正常工作。

        isgrounded = Physics2D.OverlapCircle(groundcheck.position, checkradius, ground);

地面检查是一个游戏对象,游戏对象具有具有位置的“变换”,因此请将其更改为 groundcheck.transform.position

答案 1 :(得分:-2)

对于第一条消息,字段初始化应使用恒定值。

public class you : MonoBehaviour
{
    public const float InitialSpeed = 20f; 
    public float upForce = 100f;
    public LayerMask ground;
    private Rigidbody2D rb2d;
    public float speed = InitialSpeed; // Here 
    public bool isgrounded = true;
    public float checkradius = 0.5f;
    public GameObject groundcheck;
    public float translation = Input.GetAxis("Horizontal") * InitialSpeed; // And Here

// Rest of the code

关于第二个错误,“ position”属性来自转换。 Documentation也许您是说:

isgrounded = Physics2D.OverlapCircle(groundcheck.transform.position, checkradius, ground);