Unity ошибка cs0120

У вас пока нет объекта класса RigidBody2D. Есть только сам класс, читай: шаблон, чертеж. Вы пытаетесь узнать скорость автомобиля по его чертежу. Как вам подсказывает ошибка, это можно сделать только со статическими членами класса (то есть общими для всех его объектов. Скажем, количество колес, если это класс обычных легковых автомобилей :)), а velocity, что логично, non-static member.

Вы можете взять velocity только у конкретно экземпляра класса Rigidbidy2D.

Пример. Есть тип мебели — шкаф. Шкафов — много. Но вам надо взять высоту не всех шкафов в мире, а одного конкретного шкафа. Так и тут. Rigidbody2D может быть много. Но вам нужен конкретный. Поэтому velocity не статический, и есть только у конкретного экземпляра.

Т.е. вам надо у вашего монобехейвиора найти Rigidbody2d, и у него брать велосити.

Например, так:
Rigidbody2D rigidbody = this.gameobject.GetComponent();
Vector2 velocity = rigidbody.velocity;

Это просто пример. Надо не забыть проверить на null, не делать GetComponent в апдейте. Можно вообще в инспекторе в объект положить его же Rigidbody…

Прежде чем писать игры — подучите язык…

ИМХО рано за Unity взялся. Подучи C#, прочитай хотя-бы половину какой-нибудь книжки, чтобы иметь представление о языке и ООП, а уж потом берись за Unity.
Ну а саму проблему уже описали до меня.
Вот как все исправить — добавить этот код:

priate Rigidbody2D rb;

private void Awake()
{
    rb = GetComponent<Rigidbody2D>;
}

далее везде, где у тебя в коде написано Rigidbody2D поменять это на rb

Fairly new to Unity and I’ve been getting through my game with not too many hiccups but I’m stumped on this one.
The error I’m getting is:

Assets/Scripts/Interactables/ButtonMoveObject.cs(25,55): error CS0120: An object reference is required to access non-static member `Inventory.CheckItem(Inventory.items)’

I can’t seem to figure it out, any thoughts?

using UnityEngine;
using System.Collections;

public class ButtonMoveObject : MonoBehaviour {

//Object name to link to button
public GameObject buttonReceiver = null;

//Target for moved objects and time it takes
private Vector3 source;
public Vector3 target;
public float overTime;

//Prerequesites required to operate it
public Inventory.items[] pres;

//Flag to keep checking prerequisites and check count
private bool checkFlag = true;
private int checkCount = 0;

void Use ()
{
    if (pres.Length > 0) {
        while (checkFlag) {
            checkFlag = Inventory.CheckItem(pres[checkCount]);
            if (checkCount == pres.Length) {
                if (checkFlag) {
                    checkFlag = false;
                    StartCoroutine (MoveObject ());
                }
            }
            checkCount++;
        }
    }
}

IEnumerator MoveObject()
{
    source = buttonReceiver.transform.position;
    float startTime = Time.time;
    while(Time.time < startTime + overTime)
    {
        buttonReceiver.transform.position = Vector3.Lerp(source, target, (Time.time - startTime)/overTime);
        yield return null;
    }
    buttonReceiver.transform.position = target;
}

}

EDIT:

Okay I’ve fixed it with checkFlag = player.GetComponent<Inventory>().CheckItem(pres[checkCount]);
but now I’m getting an error Assets/Scripts/Player/Inventory.cs(21,30): error CS0176: Static member Inventory.items.keycardGreen' cannot be accessed with an instance reference, qualify it with a type name instead

in my Inventory script

using UnityEngine;
using System.Collections;

public class Inventory : MonoBehaviour {

public enum items
{
    keycardGreen,
    keycardRed
};

//Inventory List
[HideInInspector]
public bool keycardGreen = false;
[HideInInspector]
public bool keycardRed = false;

public void CollectItem (items newItem)
{
    switch (newItem) {
    case newItem.keycardGreen:
        keycardGreen = true;
        Debug.Log(newItem + " collected.");
        break;
    case newItem.keycardRed:
        keycardRed = true;
        Debug.Log(newItem + " collected.");
        break;
    default:
        break;
    }
}

public bool CheckItem (items checkItem)
{
    switch (checkItem) {
    case checkItem.keycardGreen:
        return keycardGreen;
        break;
    case checkItem.keycardRed:
        return keycardRed;
        break;
    default:
        Debug.Log("Item does not exist.");
        break;
    }
}
}

Because you’re working with Unity, you need to follow the requirements of the engine.

In a case like this, where you need an instance of a component (MonoBehaviour), you really want to be referencing a Unity created instance, instead of creating a new one with the new keyword. Creating an instance of a component using the new keyword is going to leave you with an instance of the class that’s not associated with any Unity GameObject.

The far more reliant way to get the component you want to reference, is to use the Inspector window, and drag into the object field, the right component on the desired object. In this case, I am going to assume you’ll want to drag a Scene object (in your hierarchy) into the object field slot.

You would do that by first defining a variable. This can generally be done in one of two ways:

  1. public Zoney zoney;
  2. [SerializeField] private Zoney zoney;

In this example, once you’ve assigned your reference, use the variable zoney, instead of the class name Zoney. Note that your variable name could be anything else you feel is appropriate, e.g. _zoney, or myZoney.

Your new Shop script could then look like this:

    public class Shop : MonoBehaviour
    {
        public int Change;
        public Zoney zoney;
    
        void Update()
        {
          Change += 1;
          zoney.setMonney(Change);
          Debug.Log(Change);
        }
    }

Сообщество Программистов

Загрузка…


Go to Unity3D


r/Unity3D

A subreddit for News, Help, Resources, and Conversation regarding Unity, a game engine first released on June 8, 2005. Later discontinued on September 12, 2023.




Members





Online



error CS0120: An object reference is required for the non-static field, method, or property


Solved

i made a script to make the player faster the higher score you get but i got this error
Assets\Scripts\Player.cs(40,13): error CS0120: An object reference is required for the non-static field, method, or property ‘Score.score’

if (Score.score == 50)

{

SpeedUp();

}

void SpeedUp()

{

PlayerSpeed + 1;

}

does anyone know why?

Понравилась статья? Поделить с друзьями:
  • Unity ошибка cs1519
  • Unity ошибка cs1022
  • Unity ошибка cs1003
  • Unity ошибка cs0246
  • Unity ошибка cs0103