- Home /
Build auto id for any object in inspector
Hello. I have a variable called "id". I want to automatically put a randomistic number when its script is given to the object in the editor. What should I do to do this?
$$anonymous$$ay i ask what you're trying to achieve with it? What's the purpose?
$$anonymous$$ake your script executable in edit mode with adding [ExecuteInEdit$$anonymous$$ode]
attribute to your script. Then do this:
void OnEnable(){
if(Application.isEditor) //make sure to get it work only in edit mode or else it will repeat the process in runtime too
id = (int)Random.Range(0,1000) //numbers are imaginary
}
It's not entirely clear what the OP means by "when its script is given to the object in the editor" but it suggests to me that they want the randomisation to happen when the component is first added, and then not re-randomised subsequently. Your solution doesn't not achieve the latter - the OnEnable will be called again (for example) when you reload a scene with such an object in it, or after the editor has reimported assets
Two lines of solution for two lines of question :) all circumstances must be told clearly to get suggestions %100 accurate.
Answer by Hukha · Mar 14, 2019 at 01:16 PM
You can use the InstanceID of the GameObject with GetInstanceID instead of a random ID