Losing reference on my objects

Heya,

I’ve got another noob question … I’m using an array, called m_Grid, which elements are GameObjects I instantiate. They are instantiated correctly but when i want to access them later, it seems the reference is lost … Let me show you :

In a first script A, i do :

function Awake()
{
	m_Grid = new Array(g_Size );
	
	for ( var l_i = 0 ; l_i < g_Size ; l_i++ )
	{
		m_Grid[l_i] = new Array( g_Size );
	}
	
	SpawnInitialPawns();
}

In the function SpawnInitialPawns(), there is somewhere a :

m_Grid[l_x][l_y] = Instantiate( g_Pawn, l_Position, transform.rotation );

for some of the elements of my grid (the others remain at null).

At the end of the Awake function, if i do a Debug.Log( m_Grid[0][0] ), it says GameObject, so it’s just fine.

But then, in another script B, i call the following function from script A :

unction GetElement( _X : int, _Y : int ) : GameObject
{
	return m_Grid[_X][_Y];
}

And, on the return line, it says there is a NullReferenceException when i execute the code. I can’t even get to print m_Grid[_X][_Y]. I’ve already made sure _X and _Y were valid (they are actually at 0 0), I just don’t understand why I can’t access the data in my grid anymore.

Any ideas ?

Thanks.

When do you acces the GameObject you instantiate? If its in that same Awake function than you are too early. To see what happens you should add a debug.log to the Awake and Start functions of you instantiated objects. You will see that there is a difference in when those are called. From the top of my head: Awake is called on creation, Start is called when all GameObjects are created.

So if you call those GameObjects in an Awake other then their own, chances are you are too quick because the Awake of those GameObjects haven’t been called by the engine yet.

I Instantiate the objects in an Awake (in the SpawnInitialPawns method in the code i posted above). At the end of this Awake, the objects are correctly istantiated.

And then, i try to access them in the Awake of another script. I made sure this one was called after the first one but well …

I tried to access my objects in the Start instead of the Awake, but it still doesn’t work :frowning:

Ok, to make things easier, i’ll call my 2 scripts “Instantiate” and “Access” se we know what we’re talking about. I added some Debug.Logs in the Awake and Start methods of my 2 scripts, and here is what i get in my console :

AccessScript : Awake

InstantiateScript : Awake (this is where i instantiate my objects, and they are correctly instantiated)

AccessScript : Start (this is where i try to access the objects i instantiated in the InstantiateScript, and it says : NullReferenceException : Object reference not set to an instance of an object.

Does that help you to find what i’m doing wrong ?

Can you post the code that calls GetElement?