I have created an C# script and attached it to a prefab which is attached to a game object. This prefab is then placed into the hierarchy pane. Its called GOPool. GOPool has a static member variable called “Instance”. Now, as you can see in the snipped code below Instance is a self-referential variable. When I load the game the initialization routines have the expected results and Instance is not null - it is what I set it to.
Now when I try to reference GOPool.Instance from another script Instance is now null and I get a null reference exception thrown at the GOPool.Instance line.
I should mention that the sscript that references GOPool.Instance is a bullet prefab and it has " var GOPool : GameObject" at the top of the file and I drag the GOPool object from the Hierarchy pane into the area of the editor labelled “GOPool” for the bullet prefab script.
My question is this: how come my GOPool inits ok but when I reference it from another script its Instance variable is null? Are they separate objects? The ullet prefab’s script is called after all intialization has been done on the GOPool.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
/// <summary>
/// © Boon Cotter
/// You are granted non-exclusive license to do whatever
/// you want with this code.
/// </summary>
public class GOPool : MonoBehaviour
{
#region Static
/// <summary>
/// Static GOPool instance.
/// </summary>
public static GOPool Instance;
#endregion
#region Fields
/// <summary>
/// The PoolObject collection.
/// </summary>
public List<PoolObject> PoolCollection;
/// <summary>
/// The post-build collection.
/// </summary>
private Dictionary<string, PoolObject> Pool;
#endregion
#region Methods
/// <summary>
/// Local initialization.
/// </summary>
private void Awake()
{
if (Instance != null)
Destroy(this);
Instance = this;
Pool = new Dictionary<string, PoolObject>();
int counter = 0;
foreach (PoolObject po in PoolCollection)
{
Debug.Log( "GOPool: Awake(): counter: "+ counter);
Pool.Add( po.Prefab.name, po );
}
// Free memory
PoolCollection = null;
Debug.Log("PoolCollection is null? " + ( PoolCollection == null) );
Debug.Log("Instance is null? " + ( Instance == null) );
Debug.Log( "GOPool: Awake(): Num obj in Pool: " + Pool.Count );
Debug.Log( "GOPool: Awake(): Num obj in Pool: " + Pool.Count );
}
#endregion
}
The way I’m accessing it. Note that the Pop() function below has been removed from the code above for simplicity:
var bullet = GOPool.Instance.Pop( “pfBulletDeletableRaycast01” );