前言:在Unity游戏制作过程中为了方便策划调试保存 通常会让策划可以在游戏运行时直接保存调整好的预制体
在此背景下,出现了以下代码:
代码:
- public class ChangePrefabs : MonoBehaviour {
- public bool Save = false;
- public string Name;
- private string path;
- void Start() {
- Name = this.gameObject.name;
- path = string.Format("Assets/Model/{0}", Name.Replace("(Clone)", "")) ;
- }
-
- void Update() {
- if(Save) {
- Save = false;
- PrefabUtility.SaveAsPrefabAsset(this.gameObject, path);
- }
- }
- }
程序运行中修改预制体的上部球体的材质,然后点击Save,停止运行后 可以看到工程里的预制体也同样被改变了
修改前:

修改后:

点击Save

代码:
- public class ChangePrefabScript : MonoBehaviour {
- public bool Save = false;
- public string path;
- public string canChange;
- GameObject player;
- void Start() {
- player = Addressables.LoadAssetAsync
(path).Result; - }
-
- // Update is called once per frame
- void Update() {
- if(Save) {
- Save = false;
- SerializedObject thisScript = new SerializedObject(this);
- if(player != null) {
- var oldChangePrefabScript = player.GetComponent
(); - SerializedObject oldScript = new SerializedObject(oldChangePrefabScript);
- SerializedProperty serializedProperty = thisScript.FindProperty("canChange");
- oldScript.CopyFromSerializedProperty(serializedProperty);
- oldScript.ApplyModifiedProperties();
- }
- }
- }
- }
程序运行中修改预制体上的脚本中的CanChange中的内容,然后点击Save,停止运行后 可以看到工程里的预制体上的脚本中的Can Change内容随之改变了

