- Home /
NullReferenceException when assigning a parent to an instatiated object.
The game level is made of instatiated tiles and I need to make them a child of a single parent LevelDataParent but I always get a null reference exception.
void Start(){
position = new Vector2 (0, 0);
for (float i = 0; i<ySize; i++){
for (float j = 0; j<xSize; j++){
position.x = j;
position.y = i;
GameObject clonedTile = Instantiate(tilePrefab[Random.Range(0,tilePrefab.Length)], CartToIso(position), Quaternion.identity) as GameObject;
clonedTile.transform.parent = GameObject.Find("LevelDataParent").transform; //Exception is raised here
}
}
}
Thank you in advance.
Answer by Jessespike · Aug 31, 2014 at 03:56 PM
Is LevelDataParent the name of a GameObject, or a script?
GameObject.Find Finds a game object by name.
GameObject.FindObjectOfType Returns the first active loaded object of the Type.
Try this out:
clonedTile.transform.parent = GameObject.FindObjectOfType(typeof(LevelDataParent)).transform;
To expand on jessespike I would suggest using FindGameObjectByTag ins$$anonymous$$d of type or name. All three of these are pretty slow and can but Tag is optimized to be a bit faster. Even better would be to make a private static variable to store the parent ins$$anonymous$$d of finding it every time.
private static Transform m_parent = null;
private const string TRANSFOR$$anonymous$$_PARENT_NA$$anonymous$$E = "LevelDataParent";
public static Transform parent
{
get
{
if( m_parent == null )
{
m_parent = GameObject.FindGameObjectWithTag(TRANSFOR$$anonymous$$_PARENT_NA$$anonymous$$E).transform;
}
return m_parent;
}
}
Then to set the parent you go
clonedTile.transform.SetParent(parent, false);
I might have gone to far with using static but I am all about making things fast :)
Thanks for response. @Jessespike LevelDataParent is a name of a GameObejct. @b$$anonymous$$ayne .SetParent is not a native unity method. Do I need a plugin or library to call it?
Damn, I think it's only 4.6 that is was added. I have been working with 4.6 for a few months. $$anonymous$$y bad. You can just use
clonedTile.transform.parent
Your answer
Follow this Question
Related Questions
Animation Error "Null reference exception"? 2 Answers
c# 2D array error: need Help! 1 Answer
Resources.Load texture problem 1 Answer
Fresh installed , with problems 0 Answers
Passing information error 0 Answers