Search code examples
c#unity-game-enginegame-physicsgame-enginegame-development

A field initializer cannot reference the non-static field, method, or property 'EnemySpawn.MyBall


I am a beginner in game development and I have written a script to generate enemies and I want to generate enemies within 100 units of my player.

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

For some reason, I am getting this error. I tried making the MyBall static but then I am not getting the option of dragging and dropping "MyBall" in the Unity Ui where the script comes and option of selecting the enemies is only coming.

EnemySpawn.cs(10,17): error CS0236: A field initializer cannot reference the non-static field, method, or property 'EnemySpawn.MyBall'


Solution

  • The reason this doesn't compile is that you can't initialize a field (PPX) using a non static getter like this. To avoid the issue, either change it to a property (which will get called every time the value is needed:)

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

    Or simply move it before you use the value (you can leave float PPX declaration empty or initialize with 0)

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