C#错误:非静态字段,方法或属性需要对象引用 [英] C# error: An object reference is required for the non-static field, method, or property
问题描述
我希望我的玩家加快速度几秒钟.当它收集4个项目(paintCount = 4)时,玩家会在短时间内获得移动速度提升.
我在Paintser类中总是出错:SimplePlayer0.SpeedUp();
.
我已经尝试了许多方法来应对它,但是它们都没有起作用.
我在Unity工作.
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.
错误:非静态字段,方法或属性'SimplePlayer0.SpeedUp()需要对象引用.
Error: An object reference is required for the non-static field, method, or property '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;
}
}
这是加电脚本,其中的游戏对象被销毁了.
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
方法是SimplePlayer0
类的实例成员.
因此,您需要将其作为实例方法调用:
Thus, you need to call it as an instance method:
SimplePlayer0 player0 = new SimplePlayer0();
player0.SpeedUp();
这篇关于C#错误:非静态字段,方法或属性需要对象引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!