How to reset a component on duplication?

I have a component, that I want to automatically reset when the game object it is attached to is duplicated / cloned in the editor.

I have tried doing this with a stored ID, and every time you inspect the component it looks through the whole scene for other objects with the same ID and if there is one, resets itself. But this is a very clumsy way of doing it, and it's very specific (I have to individually reset every variable).

Is there a way to reset a component?

Is there a way to catch duplication?

Is it possible to do this from a custom editor instead of the component itself (lets say I don't have access to the component's script)?

more ▼

asked Oct 27, 2010 at 10:56 AM

avatar image

Orion 1
477 21 38 35

Is it supposed to be an editor duplication event, or a run-time duplication event? Have you tried calling Reset() during OnEnable() ?

Dec 06, 2010 at 02:51 PM Statement

It indeed is supposed to be editor duplication, which does not call OnEnable().

Dec 09, 2010 at 10:03 AM Orion 1
(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first

You could save the "restored" version as a prefab, and instance off of that?

more ▼

answered Oct 28, 2010 at 02:17 AM

avatar image

Max Kaufmann
623 29 25 35

Hm. Using a prefab would be tricky, as I then need very specific code to get instantiate the prefab, get the right component out of it, read its data and remove the instance again. Plus I have to create prefabs for pretty much everything.

But the most important issue for me is to catch when the duplication actually happens.

Nov 02, 2010 at 09:39 AM Orion 1
(comments are locked)
10|3000 characters needed characters left

Hmm... Have you tried:

 public class myObject : MonoBehaviour
     [NonSerialized] public bool isDuplicate = true;
     void Awake()
         myObject mo = this as myObject;
         Debug.Log( "In Awake. isDuplicate: " + myObject.isDuplicate );
         if( myObject.isDuplicate )
     void Reset()
         myObject mo = this as myObject;
         // re-set/intialize NonSerialized members, shared meshes, etc...
         myObject.isDuplicate = false;

One drawback is, Reset() will get called 2 times when you Duplicate your object in the Unity editor. Sorry. :/

more ▼

answered Dec 29, 2014 at 11:24 PM

avatar image

16 1 1 22

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here



Answers and Comments



asked: Oct 27, 2010 at 10:56 AM

Seen: 4580 times

Last Updated: Dec 29, 2014 at 11:30 PM