0

I'm using Unity and in my script I have the class Species that has the function generate. I want to call it within the start brackets but I'm getting the error message:

NullReferenceException: Object reference not set to an instance of an object Algoritm.Start () (at Assets/Scripts/Algoritm.cs:21)

Line 21 is: H[i].Generate();

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

public class Algoritm : MonoBehaviour
{
    public GameObject House;
    public const int NHouse = 20;
    public const int Xsize = 400;
    public const int Ysize = 400;
    public const int Gen = 20;
    Species[] H = new Species[Gen];


    void Start()
    {
        Debug.Log("Start");
        for (int i = 0; i < Gen; i++)
        {
            H[i].Generate();
            Debug.Log("Yes");
            Instantiate(House, H[i].Positon[i], House.transform.rotation);
        }
    }

    void Update()
    {

    }
}

public class Species
{
    private int xsize = Algoritm.Xsize;
    private int ysize = Algoritm.Ysize;

    public int[] xcor = new int[Algoritm.NHouse];
    public int[] ycor = new int[Algoritm.NHouse];
    public Vector3[] Positon = new Vector3[Algoritm.NHouse];

    public void Generate()
    {
        for (int i = 0; i < Algoritm.NHouse; i++)
        {
            xcor[i] = Random.Range(-xsize / 2, xsize / 2);
            ycor[i] = Random.Range(-ysize / 2, ysize / 2);

            Positon[i] = new Vector3(xcor[i],0,ycor[i]);

        }
    }
}
David Rogers
  • 2,601
  • 4
  • 39
  • 84
Frojden
  • 1
  • 1
  • because `H[i]` is not initialized yet – Vivek Nuna Jun 12 '20 at 12:48
  • `Species[] H = Enumerable.Range(0, Gen).Select(_ => new Species()).ToArray();` should do the trick. As said above `Species` is a class and you have not initialized them yet so `H` contains `null` pointers, giving the exception you mentioned when you try to do anything with them. You could also do `H[i] = new Species();` inside the loop before you access it. –  Jun 12 '20 at 12:50
  • Thank you very much for the answer. I don't get it 100 % why i have to do so but i tried the last example and it work. Thank you! – Frojden Jun 12 '20 at 13:32

0 Answers0