Reset an object to the prefab state

I’ve got an object that gets filled up with new components during gameplay, particularly audio components.  Do I delete the one I just used and instantiate a prefab, or do I delete the audio components off of the object I’ve been using?  I tried both ways, and I’m sure there are ways to get both to work, but the one that worked better was deleting audio components off the object.  This is because that object was referenced in other scripts’ public variables through the GUI drag&drop stuff, and if I deleted that object outright, suddenly those scripts weren’t referencing the object anymore.

Here’s the script for getting all audiosources and destroying.  (Based on stuff from http://answers.unity3d.com/questions/275714/how-to-find-all-components-of-a-game-object.html)

            // destroyed audio sources  easy peasy 
            Component[] audioSources = gameObject.GetComponents<AudioSource>();
            foreach (Component audiosource in audioSources

{
                Destroy(audiosource);
            }

<— code block isn’t working there.  Probably don’t have my SmartSyntax set up right?  Gonna switch to GitHub Gist when I have the bandwidth. #todo

Here’s the script for instantiating the prefab (based on http://forum.unity3d.com/threads/editor-script-create-game-object-from-a-prefab.47845/).  Didn’t wind up keeping this one, but it’s nice to have on file.  Also I’ve had trouble loading assets at the path (before I’ve used Resources.Load, and am now wondering which one is better for my purposes – I’ll check that out in a later post! #todo).

            Object prefab = AssetDatabase.LoadAssetAtPath(Assets/Prefabs/Answer, typeof(GameObject));
            GameObject answer = Instantiate(prefab, Vector3.zero, Quaternion.identity) as GameObject;

Leave a Reply

Your email address will not be published. Required fields are marked *