Hi,
I’m currently part of a small team that’s building a little sidescroller game for unity (this is the first time we’re messing around with it, and it shows, haha:)), and I’ve run into a rather annoying issue.
I have a gameobject which is spawned when a certain level loads, and it has a script attached to it telling it not to be destroyed whenever another level is loaded (hence dontdestroyonload). This is fundamental to the design.
However, when the level is reloaded, another gameobject of the same type is created, and this is what I’m seeking to avoid. What would be the best method around this?
The obvious solution (that my terrible programmer brain can see) would be to put this object in an empty level that only gets loaded once, but I’m hoping any of you have any better suggestions?
Give the object a specific name and the use the Start function to check if this object already exists (GameObject.find(“name”) I think was the correct syntax) and if so destroy it again ( destroy(gameObject) )
Isn’t this going to point to the original object then?
And the start function, isn’t that only executed once? Considering the fact that I am telling the object not to be destroyed upon reload (or load to another level), I don’t ever get to access that function again, do I?
I’m considering checking if more than one type of an object exists, and if it’s true, delete the one with the highest instance ID, but I am not sure if this makes any sense.
edit: didn’t mean to ninja edit my post, but I’ll give your solution a go, anyhow.
don’t think its executed again and thats exactly the point.
Only the new clone of the object is going to execute it, so only the clone will be removed as the clone is not the same object but a new one created with the scene. (at least I think)
The alternative is loading it in the background in the previous scene, independent of what it is. At least if this is possible. (preload it in the menu for example)
I ended up with an invisible load that loads in between the 2 levels, not the best solution, but it’ll do for now.
Thanks for the help, anyway.
This is the singleton pattern–you only want one instance of an object. The best way to do it in Unity is a static variable that tracks the instance.
Generally this is:
static var instance;
function Awake()
{
// instance isn't null, we aren't the first
if(instance)
{
Destroy(this);
return;
}
// otherwise we are the first, record ourselves
instance = this;
}
Other scripts usually access the singleton via YourScript.instance. There are other subtle ways to track it–instead of destroying you can do other things first, or destroy the entire GameObject. Whatever makes sense for your project.
There’s a Wiki thread on the subject, too: http://www.unifycommunity.com/wiki/index.php?title=AManagerClass
}
wow, thanks a ton, that’s even better!