- Home /
Can you retain scripts by storing them?
I'm wondering if it's possible to retain a script by storing it using GetComponent() and then destroying the object. What happens to the script, and could that script be used to replace the equivalent script in a later instance of the object?
GetComponent() doesnt actually store or get the Script itself, all it does is returns a Reference to where that Script is located so that you can access it later.
Perhaps you could just store the Data you want in another fashion so that you can reload it later.
Yea honestly the approach I would take if its a simple script, would be to have a empty object to store it to, then destroy it. You could even use the same script and just reference the values before destroying the one you're getting rid of - but that could get costly if its massive.
Answer by Nanobrain · Mar 05, 2014 at 11:30 PM
When destroying the object, I believe the reference to the script is destroyed as well. Thus, after destroying the object, if you then try to access the variable that contains the script, you'll probably get a null reference exception.
If not, then in order to pass the data from the 'saved' script into a new object, you would need to write a constructor for the class that takes an object of type (it's class name), and then extracts the data from the given script into itself.
It's worth a shot. If it works, it seems like a good way to preserve data.
This seems like the job for encapsulation (except that the data is no longer exposed to the inspector).
You should be able to expose the encapsulated classes' data by customizing the class' editor.
Your answer