- Home /
Changing a script inside a prefab
I'm working off a solution I found here: http://answers.unity3d.com/questions/867714/changing-prefab-setting-through-scripting-c.html
I have a prefab which has a script, I am trying to change the public values of that script. I am trying to access the script using the GetComponent function, but it just keeps yelling at me that object reference is not set to an instance of an object and now I am scared ;_;
Just to be clear, I want to change the script inside the prefab itself, not an instantiated object of the prefab.
Here's the script: http://hastebin.com/itazovapuy.py
Are you looking to change the script of the prefab during runtime, or just in the editor?
check this thread:
Yeah, that's a good link. That's why I asked if this was for runtime or not. To my knowledge there is no way to get this to work during runtime, however if I'm wrong I would love to know how!
You can make it work with a workaround: Instantiate the prefab, change the script, then use PrefabUtility to replace the prefab with the changed one. Works only when running from the editor, though.
On a related note, changing prefabs at runtime goes contrary to the purpose of prefabs.
Answer by robbyisdead · Sep 29, 2015 at 10:53 PM
Hello Mako,
So here, it looks like you're trying to grab a component from an object:
EnemyHealth eh = prefabs[0].GetComponent();
And if you'e getting a null object reference, it means this ^ isn't getting anything. A better way would be to declare a global variable for the script, like this:
private NameOfScriptYouAreTryingToEdit variableName;
Then you call that in the script like this:
variableName.EnemyHealth.
Your answer
Follow this Question
Related Questions
Pressing Apply Breaks Prefab 1 Answer
How to find the prefab base of a Prefab Variant through code? 1 Answer
Reinitialize prefab 0 Answers