Unity Losing Object References and Duplicating Objects
Hi there,
So I have a script with the ExecuteInEditMode attribute. This allows me perform design tasks in the editor and setup my scene, prior to pressing play.
The script itself is attached to a UI Canvas. There's nothing in the canvas until Start is called, then it creates a bunch of things, but to simplify this question let's just assume it creates a button.
All is fine, until I press play, all of the existing object references break so that it no longer believes it has performed the code in Start, and does it again, which duplicates the objects. So I now have 2 buttons in the canvas.
When I press play again to stop the game, I still have 2, if I press Start again, it creates another new button, so now I have 3 and so on and so forth.
So I've tried the following so far,
Using a boolean variable which is set to true when the button is created. This doesn't work as when Start is pressed, the variable switches back to false every time.
Creating a child object called "Initialised" when the button is created on Start. Also at the beginning of Start, I check to see if this object already exists before I create the button. This seemed to work to start with, but for some reason, isn't now.
Deleting all child objects at the beginning of Start so that the rest of the method can make the button without concern. This hasn't worked either and Unity seems to get quite confused about the whole situation.
How on earth do you make a script that creates child objects
There must be a way to do this but I'm obviously doing something very wrong.
Any ideas? Thanks in advance.
Nick.
Answer by firkinfedup · Apr 14, 2018 at 06:59 PM
Okay I have a solution,
private GameObject _initialisedObject;
public Boolean IsInitialised
{
get
{
Transform initTransform = transform.Find("Initialised");
_initialisedObject = initTransform != null ? initTransform.gameObject : null;
_isInitialised = _initialisedObject != null;
return (_isInitialised);
}
}
private void Initialise()
{
if (!IsInitialised)
{
//Create any necessary child objects here
//remember to set the parent to this.transform
_initialisedObject = new GameObject("Initialised");
_initialisedObject.hideFlags = HideFlags.HideInHierarchy;
_initialisedObject.transform.SetParent(transform);
}
}
Initialise is called on Startup.