Wyeknott
Wyeknott

Reputation: 116

Cannot reference a script on an array of gameobjects generated in another script

I want an array of game objects, each game object has a simple script to move it. I want a controlling script to be able to trigger the remote script by referencing the array coordinates / game object at that point.

I am missing something basic in referencing a "global" variable - so apologies in advance. I have spent several hours now reading and trying things out. Example questions like here Accessing a variable from another script C# or https://answers.unity.com/questions/42843/referencing-non-static-variables-from-another-scri.html

I believe the array should be static as there is only one set of data, however I don't care if it isnt

CreateGrid.cs

public class CreateGrid : MonoBehaviour
{

public static GameObject[,] gridArray = new GameObject[5, 5];
public GameObject gridSpace;

// Start is called before the first frame update
void Start()
{
    GenerateGrid();
}

void GenerateGrid()
{
    for (int x = 0; x < 5; x++)
    {
        for (int z = 0; z < 5; z++)
        {
            gridArray[x, z] = Instantiate(gridSpace, new Vector3(x, 0, z), Quaternion.identity) as GameObject;
        }
    }

    // test grid works
    // gridArray[2, 2].transform.Translate(0.0f, 3.0f, 0.0f);
}

}

test code

public class Pulse : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {

     for (int x = 0; x < 5; x++)
        {
        CreateGrid.gridArray[x, 3].GetComponent<MoveObject>().StartBounce(5.0f);
        }
    }
}

The grid of objects works. However the test code errors with Object reference not set to an instance of an object from the line CreateGrid.gridArray[x, 3].GetComponent().StartBounce(5.0f);

specifically CreateGrid.gridArray

Given that I seem to be really struggling with a concept, please explain clearly.

Thanks

Upvotes: 0

Views: 232

Answers (1)

Hellium
Hellium

Reputation: 7356

Unless you don't clearly define otherwise, you don't know when the Start method of two MonoBehaviours will run.

In your case, the Pulse's Start method is called before CreateGrid's.

To fix your problem, I advise you to call CreateGrid's Generate method inside the Awake method of the class.

I often use this method to initialize members of the class not relying on other classes instances and use the Start method to initialize members needing other instances to be self-initialized.

Upvotes: 1

Related Questions