字段初始值设定项不能引用非静态字段、方法或属性 'EnemySpawn.MyBall



我是游戏开发的新手,我写了一个生成敌人的脚本,我想在玩家的100个单位内生成敌人。

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

public class EnemySpawn : MonoBehaviour
{
public GameObject[] enemies;
public GameObject MyBall ;
float PPX = MyBall.transform.position.x; // Player's position on x axis
int randEnemy;
int i = 0;
void Update()
{
Debug.Log("The position of ball is" + PPX);
if (i % 30 == 0)
{
Debug.Log("The position of ball is" + PPX);
i++;
randEnemy = Random.Range(0, 6);
Vector3 randomSpawner = new Vector3(Random.Range(-PPX - 100, PPX + 1), 1, Random.Range(-PPX - 100, PPX + 1));
Instantiate(enemies[randEnemy], randomSpawner, Quaternion.identity);

}
else
{
i++;
}      
}
}

由于某种原因,我得到了这个错误。我试着让MyBall静态,但后来我没有得到拖放MyBall的选项;在Unity Ui中,只有脚本和选择敌人的选项才会出现。

EnemySpawn.cs(10,17):错误CS0236:字段初始化器不能引用非静态字段、方法或属性"EnemySpawn"。MyBall '

无法编译的原因是您不能使用像这样的非静态getter来初始化字段(PPX)。为了避免这个问题,可以将其更改为一个属性(每次需要该值时都会调用该属性:)

float PPX { get { return MyBall.transform.position.x; }}

或者在使用值之前简单地移动它(您可以将float PPX声明为空或初始化为0)

float PPX = 0;
(...)
if (i % 30 == 0)
{ 
PPX = MyBall.transform.position.x; 
(...)

最新更新