Home > OS >  Unity2D: my instantiate random object is still error even if I attached a scripts to it
Unity2D: my instantiate random object is still error even if I attached a scripts to it

Time:12-07

I'm currently making a simple game for my project, which is spawning food and damaging it until its vanishes. I have to write a script that instantiates a random object from an array, attaches the script to it, and damages the instantiated food in another script. The current problem now is Unity telling me that I have a Null Reference Exception on both scripts, I tried to fix it by attaching the script to the instantiated object, but still, the problem remains.

Here the code on the script that attaches to the instantiated object, and also spawning the object too: `

public class Food : MonoBehaviour
{
    public GameObject[] food;
    public Vector3Int spawnPosition;
    public int health = 200;
    public int currentHealth;

    private GameObject clone;

    public void Start()
    {
        currentHealth = health;
        SpawnFood();
    }

    //Spawning food 
    public void SpawnFood()
    {
        int random = Random.Range(0, food.Length); //Null Reference Exception happen in this line.
        clone = Instantiate(food[random], this.spawnPosition, Quaternion.identity) as GameObject;

        clone.AddComponent<Food>();
    }

    public void TakeDamage(int damage)
    {
        currentHealth -= damage;

        //play hurt effect

        if(currentHealth < 0)
        {
            Vanish();
        }
    }

    void Vanish()
    {
        Debug.Log("Vanished");
    }
}

`

Here is the other script: `

public class Board : MonoBehaviour
{
    public Tilemap tilemap { get; private set; }
    public Piece activePiece { get; private set; }
    public TetrominoData[] tetrominoes;
    public Vector3Int spawnPosition;
    public Vector2Int boardSize = new Vector2Int(10, 20);
    public int damage;

    public Food clone;

    public TextMeshProUGUI hud_score;

    public static int currentScore = 0;

    public int scoreOneLine = 40;
    public int scoreTwoLine = 100;
    public int scoreThreeLine = 300;
    public int scoreFourLine = 1200;

    private int numberOfRowsThisTurn = 0;

    public RectInt Bounds
    {
        get
        {
            Vector2Int position = new Vector2Int(-this.boardSize.x / 2, -this.boardSize.y / 2);
            return new RectInt(position, this.boardSize);
        }
    }

    private void Awake()
    {
        this.tilemap = GetComponentInChildren<Tilemap>();
        this.activePiece = GetComponentInChildren<Piece>();

        //call Tetromino.Initialize() to spawn pieces
        for (int i = 0; i < this.tetrominoes.Length; i  )
        {
            this.tetrominoes[i].Initialize();
        }
    }
        
    private void Start()
    {
        SpawnPiece();
    }

    private void Update()
    {
        UpdateScore();
        UpdateUI();
    }

    public void UpdateUI()
    {
        hud_score.text = currentScore.ToString();
    }

    public void UpdateScore()
    {
        if(numberOfRowsThisTurn > 0)
        {
            if(numberOfRowsThisTurn == 1)
            {
                ClearedOneLine();
            } 
            else if (numberOfRowsThisTurn == 2)
            {
                ClearedTwoLine();
            } 
            else if (numberOfRowsThisTurn == 3)
            {
                ClearedThreeLine();
            } 
            else if (numberOfRowsThisTurn == 4)
            {
                ClearedFourLine();
            }

            numberOfRowsThisTurn = 0;
        }
    }

    public void ClearedOneLine()
    {
        currentScore  = scoreOneLine;

        clone.GetComponent<Food>().TakeDamage(10); //Null Reference Exception happen in this line.
    }

    public void ClearedTwoLine()
    {
        currentScore  = scoreTwoLine;

        clone.GetComponent<Food>().TakeDamage(20); //Null Reference Exception happen in this line.
    }

    public void ClearedThreeLine()
    {
        currentScore  = scoreThreeLine;

        clone.GetComponent<Food>().TakeDamage(40); //Null Reference Exception happen in this line.
    }

    public void ClearedFourLine()
    {
        currentScore  = scoreFourLine;

        clone.GetComponent<Food>().TakeDamage(80); //Null Reference Exception happen in this line.
    }

`

Please help and thank you for the help.

Here is the Inspector image, when I save the code: Inspector Result

I have tried to attach the script to the instantiated object when that object is being spawned.

CodePudding user response:

I don't see food set anywhere. You need to populate the array inside Food from the Inspector or at least, populate programmatically in Food.Start() before using it.

Can you also show us a printscr of the Inspector view where Food is attached as component? The main focus here is the food array.

CodePudding user response:

the food array is empty it should be filled by you, instantiate doesn't fill it, it takes an object from the array and spawn it. fill it with prefabs of foods that already has the food component no need to add it in code

  • Related