OnInstantiate()???

Hello,
I was wondering if there is a function for MonoBehaviour, where when an object gets instantiated, all the scripts of that object, child objects, grandchild objects etc., calls a function to do certain tasks.

I have a scenario, where I have a C# script called ‘SeedStamp’, with 2 variables in them called ‘seed’ and ‘seedFinal’ where random seeds for each objects that have the SeedStamp script attached, are based on the seedFinal variable of that script.

seedFinal is based on seed, but I also have seedFinal multiply itself as the script looks for other SeedStamp scripts as it moves upwards towards the root object and looks for the SeedStamp script of each object and multiplies it by the value of ‘seed’ of that script, until the original SeedStamp script finds the root object. Then, that is the final value of seedFinal.

My goal is to only do that once and disable the script once seedFinal is calculated. (the original value before calculation being -1), so when seedFinal is not -1, the script disables. This saves lots of speed for my game, but when the parent objects instantiate, the seedFinal values of the child scripts also instantiate along with it.

Rather than having to look for multiple child objects and grandchildren objects that contain the SeedStamp script, setting each value of seedFinal to -1 and re-enabling the script (to recalculate the value of seedFinal), it would be nice if there was a special MonoBehaviour function in SeedStamp that calls itself to do the work every time a parent or grandparent, etc. above the script gets instantiated. Is there a way to do this? Alternatively, is there a special Monobehaviour function to where if any parent or grandparent changes ITS parent, a function gets called?

Thank you,
Michael S. Lowe

Well, you have Awake, Start, OnEnable and so on.

If we’re talking about a system where the parent instantiates these objects, then you have the control. Instantiate the object and call a method right after.

If you need to respond to the user making changes in the editor, hook into ObjectChangeEvents.

I did not really understand your use case, but it sounds an awful lot like it would work better if it were architected differently. The scripts could request a seed from a central registry for instance. Perhaps this seed provider merely needs to be a static class rather than a component. I’m sure there are ways to untangle this in a better way than for you to monitor object creation/deletion.

In the time it took to write the above you could have done GetComponentsInChildren<T>() and called your own custom endpoints in all your children, doing it from an Awake() method in your script.

You could be moving onto new stuff already! :slight_smile:

1 Like