简体   繁体   中英

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

I want my player to give a speed boost for a few seconds. When it collects 4 items (paintCount = 4), the player gets a movement speed boost for a short period of time. I always have an error in the class Paintser: SimplePlayer0.SpeedUp(); . I've tried many things to counter it, but none of them are working. I'm working in Unity.

Error: An object reference is required for the non-static field, method, or property 'SimplePlayer0.SpeedUp().

This is the players script:

using UnityEngine;
using System.Collections;

public class SimplePlayer0 : MonoBehaviour
{

  // SPEEDVARIABLES
  public static float speed = 3.5f;


  // BONUSSPEED
  private static float speedBoostTime;
  public static float SpeedBoostTime
  {
    get
    {
      return speedBoostTime;
    }
    set
    {
      speedBoostTime = value;
    }
  }



   // BONUSSPEED
   public void SpeedUp()
  {
    speed *= 2;
    SpeedBoostTime = 3; // seconds
  }

   void Update()
   {
    // BONUSSPEED
    while (speedBoostTime > 0)
    {
     speedBoostTime -= Time.deltaTime;
     if (speedBoostTime <= 0) speed /= 2;
    }
  } 

This is the power up script, where the gameobject gets destroyed.

using UnityEngine;
using System.Collections;

public class PowerUp : MonoBehaviour
{
  void OnTriggerEnter2D(Collider2D other)
  {
    if (other.tag == "Player")
    {
      Paintser.ExtraTime();
      Destroy(this.gameObject);
      Paintser.paintCount++;
    }
  }
}

And finally the script where all the magic (or errors) happens:

using UnityEngine;
using System.Collections;

public class Paintser : PowerUp
{

  public static int paintCount = 0;
  public int speedBoostTime = 3;

  public static void ExtraTime()
  {
    if (paintCount == 4)
    {

      SimplePlayer0.SpeedUp();

      Paintser.paintCount = Paintser.paintCount = 0;

    }
  }
}

SpeedUp method is an instance member of SimplePlayer0 class.

Thus, you need to call it as an instance method:

SimplePlayer0 player0 = new SimplePlayer0();
player0.SpeedUp();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM