【问题标题】:C# error: An object reference is required for the non-static field, method, or propertyC# 错误:非静态字段、方法或属性需要对象引用
【发布时间】:2015-03-02 00:19:38
【问题描述】:

我想让我的播放器在几秒钟内提高速度。当它收集 4 个项目 (paintCount = 4) 时,玩家会在短时间内获得移动速度提升。 我在 Paintser 类中总是有一个错误:SimplePlayer0.SpeedUp();。 我已经尝试了很多方法来对抗它,但它们都不起作用。 我在 Unity 工作。

错误:非静态字段、方法或属性“SimplePlayer0.SpeedUp() 需要对象引用。

这是播放器脚本:

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;
    }
  } 

这是游戏对象被销毁的加电脚本。

using UnityEngine;
using System.Collections;

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

最后是所有魔法(或错误)发生的脚本:

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;

    }
  }
}

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    SpeedUp 方法是SimplePlayer0 类的实例成员

    因此,您需要将其作为实例方法调用:

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

    【讨论】:

    • 错误消失了,谢谢。不幸的是,我的播放器并没有突然变得更快。
    • @ToondeJonge 我明白了...嗯,实际上我不是 Unity 开发人员,但我发现我可以在这个通用问题上为您提供帮助:D
    • 这是我必须面对的斗争。我会在最后找到答案^^
    • @ToondeJong 响应您的速度提升不适用,验证您的代码在方法 'SpeedUp();'被正确调用。它看起来是这样,但我没有看到速度提升是如何以任何方式应用于角色移动的。您需要以某种方式将此应用到他的角色控制器或变换。
    • 我没有上传球员运动的部分。它在 SimplePlayer0 类中。我只需要参考玩家的速度,对吧?加成速度一开始是有效的,但是当我想用时间限制来控制它时,它就不起作用了。
    猜你喜欢
    • 2012-05-03
    • 1970-01-01
    • 2012-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多