Error cs0120 unity

Добрый день, уважаемые форумчане!

Добрый день, уважаемые форумчане!

Несколько лет писал на JS, сейчас переписываю проекты на C#, столкнулся с непоняткой.

Есть скрипт1, отвечающий за обновление данных в UI-элементах (в данном случае просто меняет текст в textName на «test»).
К textName прикреплен в инспекторе UI Text.

Используется csharp

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Main : MonoBehaviour {

        public Text textName;

        public static void updatePanel()
        {
                textName.text = «test»;
        }
}

Main.updatePanel() вызывается в других скриптах, чтобы когда нужно — обновить данные в UI элементах.

Итог: Assets/Main.cs: error CS0120: An object reference is required to access non-static member `Main.textName’

Конечно же, если написать:

Используется csharp

public static Text textName;

ошибка исчезает, но тогда теряется привязка в инспекторе к UI элементу.

Я понимаю, что ошибка примитивная, но уже пол день бьюсь с ней. Подскажите, где я ошибся?
Спасибо заранее.

In Unity 5.0, I get the following error because of the code I wrote below. Unfortunately, I don’t get it, can anyone help please ?

moneyGet.cs(19,17): error CS0120: An object reference is required to access non-static member `moneySystem.money’

using UnityEngine;

public class moneyGet : MonoBehaviour
{
    int curHealth = 100;

    int maxHealth = 100;

    public void Update()
    {
        if ( curHealth > maxHealth )
        {
            curHealth = maxHealth;
        }

        if ( curHealth < 0 )
        {
            curHealth = 0;

            moneySystem.money += 100;//name of your script moneySystem
        }

    }
}

However, the following code doesn’t throw any error :

using UnityEngine;

public class moneySystem : MonoBehaviour
{    
    public int money = 0;//amout of your money

    GUIText moneyText;//To Display Your money    

    void Update()
    {
        if ( money < 0 )
        {
            money = 0;

        }
    }
}

Hellium's user avatar

Hellium

7,0352 gold badges18 silver badges48 bronze badges

asked Mar 25, 2015 at 11:21

GamingBanana's user avatar

4

Or, depending on your intended context of the game’s duration, you could make your moneySystem class a STATIC class so it is always available for entire game duration without «loosing» object reference… make the properties on it static too.

public static class moneySystem : MonoBehaviour {

   public static int money = 0;//amout of your money

   GUIText static moneyText;//To Display Your money
   ... rest of class...

Then if you had other elements, game scenes, etc, you would not have to worry about trying to instantiate them and oops forgot, or by reinstantiating them loose any previous «money» values.

answered Mar 25, 2015 at 11:29

DRapp's user avatar

DRappDRapp

47.2k12 gold badges71 silver badges142 bronze badges

I don’t know Unity so I can’t comment on the overall design, but like the compiler tells you, you need a reference to moneySystem, as its money peroperty isn’t static.

So you can instantiate a moneySystem in moneyGet‘s constructor:

public class moneyGet
{
    private moneySystem _moneySystem;

    public moneyGet()
    {
        _moneySystem = new moneySystem();
    }
}

Then in Update() you can do _moneySystem.money += 100;.

answered Mar 25, 2015 at 11:24

CodeCaster's user avatar

CodeCasterCodeCaster

144k23 gold badges215 silver badges263 bronze badges

У вас пока нет объекта класса 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

Содержание

  1. error CS0120: An object reference is required to access non-static member `Healthbar.health’
  2. 4 Ответов
  3. Ваш Ответ
  4. Welcome to Unity Answers
  5. Подписаться на вопрос
  6. Error CS0120
  7. 2 Ответов
  8. error CS0120: An object reference is required to access non-static member
  9. 1 Ответ
  10. Ваш Ответ
  11. Welcome to Unity Answers
  12. Подписаться на вопрос

error CS0120: An object reference is required to access non-static member `Healthbar.health’

Need to access my health bar script from another script so can trigger an animation . When try to access the health bar I get t$$anonymous$$s error : (19,31): error CS0120: An object reference is required to access non-static member `Healthbar.health’

Here is both scripts : Health bar script :

4 Ответов

Ответ от aditya · 09/09/16 05:08

AFAIK you can’t access non-static members through static members . in your case, in class ss you’ve made a static variable named healthbar and trying to access the non-static variable of class healthbar

Ответ от Lilius · 09/09/16 10:35

In your Healthbar script you have «public static int playersHealth» and you never do anyt$$anonymous$$ng with it.

Try putting t$$anonymous$$s to your Healthbar script Update: playersHealth = health;

And in your ss script change line 19 to: if (Healthbar.playersHealth

I suppose t$$anonymous$$s might be how you wanted to do it, because you declare static variable playersHealth. You also don’t need reference to Healthbar script since the playersHealth is static.

Ответ от AurimasBlazulionis · 09/09/16 12:46

You made a typo in ss script. You need to make it start from the lower case h. It happens sometimes when you call instances the same name of the class. To avoid confusion make the instance variable called health or somet$$anonymous$$ng not the name of the class. Also make that healthbar variable w$$anonymous$$ch points to Healthbar class non static.

Ответ от tanoshimi · 09/09/16 13:28

If you read the full error message, it tells you in what script and what line the error occurs. It’s line 19 of ss.cs

Also, I seriously recommend you get rid of any static access modifiers and naming your classes somet$$anonymous$$ng more descriptive than just «ss»

Ваш Ответ

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Подписаться на вопрос

Ответы Ответы и комментарии

79 пользователей подписаны.

Источник

Error CS0120

I’m kinda new to C# programming, but I’ve done extensive C/C++ programming. My problem seems really simple, but every solution I find online doesn’t work. I get the Error CS0120

Error CS0120: An object reference is required for the non-static field, method, or property ‘SewerRooms.r’ (CS0120) (Assembly-CSharp-firstpass)

What I’m trying to create is a text game. The SewerRooms is the file I’m using to set up the rooms to explore. I have a seperate class file: GlobalVars, to handle the «global» variables. The entire GlobalVars file is as follows:

I’ve tried the class as static, I’ve tried it the way its posted without being static. I’ve tried accessing the variable directly, and I’ve tried, as shown, to use a property with a singleton.

In the SewerRooms file I try to call the GetRooms property like so:

From that point, and the later usage of the variable ‘r’, I get the CS0120 error. Any help would be appreciated.

2 Ответов

Ответ от Berenger · 30/06/12 04:30

The way you declared SewerRooms.Start implies that it can be called without an instance of SewerRooms. However, r does.

The function Start, when you inherit from MonoBehaviour, is called by Unity at the proper moment (when the scene starts, on all the enabled script attached to an activated game object). You don’t need it to be static or public.

As for the class GlobalVar, unless you intend to attach it to a gameObject for holding resources, or to implement Update, or to use coroutines on it, you don’t need to inherite from anyt$$anonymous$$ng.

Источник

error CS0120: An object reference is required to access non-static member

t$$anonymous$$s line on my code

working ok on the manager script put when i moving it to other script and trying to accessing to it fromm other script i get t$$anonymous$$s error

Assets/Scripts/mySecondCanvas11.cs(24,49): error CS0120: An object reference is required to access non-static member `BoardManager.SpawnChessman(int, int, int)’

1 Ответ

Ответ от stanogg · 26/08/16 19:28

You need a reference to the BoardManager class as its not static. Add t$$anonymous$$s to your class:

and then use it like that

or you can use a singleton pattern if you always have only one board manager in your scene.

and access it like that :

hope t$$anonymous$$s helps!

Ваш Ответ

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Подписаться на вопрос

Ответы Ответы и комментарии

6 пользователей подписаны.

Источник

description title ms.date f1_keywords helpviewer_keywords ms.assetid

Compiler Error CS0120

Compiler Error CS0120

07/20/2015

CS0120

CS0120

3ff67f11-bdf9-436b-bc0c-4fa3cd1925a6

Compiler Error CS0120

An object reference is required for the nonstatic field, method, or property ‘member’

In order to use a non-static field, method, or property, you must first create an object instance. For more information about static methods, see Static Classes and Static Class Members. For more information about creating instances of classes, see Instance Constructors.

Example 1

The following sample generates CS0120:

// CS0120_1.cs
public class MyClass
{
    // Non-static field.
    public int i;
    // Non-static method.
    public void f() {}
    // Non-static property.
    int Prop
    {
        get
        {
            return 1;
        }
    }

    public static void Main()
    {
        i = 10;   // CS0120
        f();   // CS0120
        int p = Prop;   // CS0120
    }
}

To correct this error, first create an instance of the class:

// CS0120_1.cs
public class MyClass
{
    // Non-static field.
    public int i;
    // Non-static method.
    public void f() { }
    // Non-static property.
    int Prop
    {
        get
        {
            return 1;
        }
    }

    public static void Main()
    {
        var mc = new MyClass();
        mc.i = 10;
        mc.f();
        int p = mc.Prop;
    }
}

Example 2

CS0120 will also be generated if there is a call to a non-static method from a static method, as follows:

// CS0120_2.cs
// CS0120 expected
using System;

public class MyClass
{
    public static void Main()  
    {  
        TestCall();   // CS0120
   }

   public void TestCall()
   {
   }
}

To correct this error, first create an instance of the class:

// CS0120_2.cs
// CS0120 expected
using System;

public class MyClass
{
    public static void Main()
    {
        var anInstanceofMyClass = new MyClass();
        anInstanceofMyClass.TestCall();
    }

    public void TestCall()
    {
    }
}

Example 3

Similarly, a static method cannot call an instance method unless you explicitly give it an instance of the class, as follows:

// CS0120_3.cs
using System;

public class MyClass
{
   public static void Main()
   {
      DoIt("Hello There");   // CS0120
   }
  
   private void DoIt(string sText)
   {
      Console.WriteLine(sText);
   }
}

To correct this error, you could also add the keyword static to the method definition:

// CS0120_3.cs
using System;

public class MyClass
{
   public static void Main()
   {
      DoIt("Hello There");   // CS0120
   }
  
   private static void DoIt(string sText)
   {
      Console.WriteLine(sText);
   }
}

See also

  • The C# type system

Rigidbody2D, with an uppercase ‘R’, refers to a type. So any call of a member function with just a type is necessarily a static function call, which doesn’t require an instance. But AddForce() is not a static function, and absolutely requires an instance.

Most likely, you want to use the instance of a Rigidbody2D class that is already attached to the same game object that your BallControl script is attached to. In earlier versions of Unity, you could simply access the rigidbody2D property (note the lowercase ‘r’) of the MonoBehavior base class. So simply using the lowercase ‘r’ instead of uppercase would fix the problem, as long as your game object did indeed have a Rigidbody2D component attached to it.

In newer versions of Unity, these properties were deprecated because they encouraged less performant code patterns. Instead, you should use the GetComponent<Rigidbody2D>() call that is a part of the MonoBehavior base class. And if you access this component on a regular basis in your script, it can be prudent to create a private field that will store a reference to the component, and initialize this field in your Start() method (or the Awake() method under some circumstances).


public class BallControl : MonoBehaviour
{
    int waitSeconds = 2;
    Rigidbody2D rigidbody2D;
 
    // Use this for initialization.
    void Start ()
    {
        rigidbody2D = GetComponent<Rigidbody2D>();
        hi(20f);
        GoBall();
    }
 
    IEnumerator hi(float secs)
    {
        yield return new WaitForSeconds(secs);
    }
       
    // Generates random value, and decides which way to knock the ball based on it.
    void GoBall ()
    {
        float rand = Random.Range(0.0f, 100.0f);
 
        if (rand < 50.0f)
        {
            rigidbody2D.AddForce(new Vector2(20.0f, 15.0f));
        }
 
        else
        {
            rigidbody2D.AddForce(new Vector2(-20.0f, -15.0f));
        }
    }
}

«We should have a great fewer disputes in the world if words were taken for what they are, the signs of our ideas only, and not for things themselves.» — John Locke

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Error cs0120 an object reference is required for the non static field method or property
  • Error cs0119 gameobject is a type which is not valid in the given context
  • Error cs0119 expression denotes a type where a variable value or method group was expected
  • Error cs0118 editor is a namespace but is used like a type
  • Error cs0117 unity

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии