Changing prefab instances through script
I made a prefab gameObject with a rigidbody component attached. Whenever I change the mass of the original prefab from the inspector, all the instances present in the scene get affected (the field is not overridden). But when I try to do the same thing using a script, the mass of the instances remain unchanged (only the main prefab is affected and every time I enter play mode, it retains its previous value!). The script is attached to another gameObject and looks like this:
public class CubeScript : MonoBehaviour {
public GameObject largeCube; // dragged the original prefab in the inspector
private Rigidbody rb;
// Use this for initialization
void Start ()
{
rb = (Rigidbody) largeCube.GetComponent ("Rigidbody");
rb.mass = 44; // this is not changing the instances, rather only the main prefab. Note that the mass is not overridden
}
}
I don't understand as a beginner. The tutorials say that it is the same whether you change something from the inspector or using a script like that. Please explain this to me.
Answer by JedBeryll · Dec 09, 2015 at 04:43 PM
That is probably disabled at runtime on purpose to prevent unexpected behaviour. As you just dragged the prefab in the inspector, largeCube references the saved prefab not an actual object in the scene. If you want to change the instance's value then you need to have a reference to an instance in the scene. If you want to change all instance's values, you should use a list or an array to reference all of your instance's and iterate through them and change them one by one.
That is probably disabled at runtime
That is correct. When I enter play mode and change the original prefab it doesn't change the instances when the game is running, but whenever play mode is exited the instances immediately get those value that are changed while the game was running! For script, why didn't the same happen?
It doesn't happen because the editor changes the values. It is an editor feature not a runtime thing. The editor serializes the prefab when you change it and it knows it should change all instances too. At runtime, your scripts just do what they are told to do, and they don't check if the original prefab on the hard drive was changed or not.
Your answer