- Home /
Why can't I pass an array reference to another array variable?
So I wrote a simple ObjectPooling script that has just an array containing the objects I want to use. Problem is that I created another script called TestPool that recieves a reference of the array created in the ObjectPooling script and it does not work. Here is the ObjectPool script:
`[HideInInspector] public GameObject[] sharks;
public int numberOfObjectsToCreate = 35;
// Use this for initialization
void Start () {
sharks = new GameObject[numberOfObjectsToCreate];
InstantiateSharks();
//Debug.Log (sharks.Length);
}
// Update is called once per frame
void Update () {
}
private void InstantiateSharks(){
for(int i = 0; i < numberOfObjectsToCreate; i++){
if(i <= 7){
sharks[i] = Instantiate (Resources.Load ("Prefabs/Sharks/OpenMouthShark")) as GameObject;
sharks[i].SetActive(false);
} else if(i <= 14){
sharks[i] = Instantiate (Resources.Load ("Prefabs/Sharks/BossShark")) as GameObject;
sharks[i].SetActive(false);
} else if(i <= 21){
sharks[i] = Instantiate (Resources.Load ("Prefabs/Sharks/CloseMouthShark")) as GameObject;
sharks[i].SetActive(false);
} else if(i <= 28){
sharks[i] = Instantiate (Resources.Load ("Prefabs/Sharks/BioShark")) as GameObject;
sharks[i].SetActive(false);
} else
sharks[i] = Instantiate (Resources.Load ("Prefabs/Sharks/SkeletonShark")) as GameObject;
sharks[i].SetActive(false);
}
}
}`
and the other script:
using UnityEngine;
using System.Collections;
public class TestPool : MonoBehaviour {
public GameObject[] shark;
public ObjectPool objpool;
// Use this for initialization
void Awake(){
objpool = GameObject.Find("ObjectPool").GetComponent<ObjectPool>();
shark = objpool.sharks;
Debug.Log (shark.Length);
}
}
The line "Debug.log(shark.Length);" is supposed to return a value other that 0, but it does not...
Please Help me!!!
Answer by whydoidoit · Feb 17, 2014 at 03:36 AM
You are assigning the array in the Awake function of the TestPool script.
Unity is making an empty array of GameObjects in the construction phase of the ObjectPool script, which you are overwriting in the Start function of that script.
Your TestPool script is getting the initial empty array, because you are doing that in Awake.
You must ensure that the assignment is done before you need the result.
So either:
Move the construction of the GameObject array to the Awake function of the ObjectPool script and move the TestPool assignment to Start
Have them both in the same function (either Start or Awake for both) and set the script execution order using the Editor to have ObjectPool run first.
Your answer
![](https://koobas.hobune.stream/wayback/20220613133749im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Gui placement help 1 Answer
Yield function goes slow sometimes/differently? 2 Answers
How can i fix this error? 2 Answers
OnCollisionEnter called twice 2 Answers