- Home /
Question by
cgbrown-mos · Dec 05, 2017 at 10:24 PM ·
scripting problemsceneeditor-scriptingcontextmenu
How to save field changes to scene file using ContextMenu?
Hi!
I am trying to the modify a field on a MonoBehavior using a ContextMenu script and then saving the new value to the scene file, but I cannot figure out how to make the saving work.
The field I am trying to modify is a file name and I am using the ContextMenu script in the Editor to fill in this field with the name and extension of the sprite attached to the Image component on the Game Object.
The code I have so far is below:
public class StreamingText : MonoBehaviour {
[SerializeField] private string fileName;
private Image uiImage;
[ContextMenu("Rename With File Extension")]
private void RenameWithFileExtension()
{
#if UNITY_EDITOR
uiImage = gameObject.GetComponent<Image>();
fileName = Path.GetFileName(AssetDatabase.GetAssetPath(uiImage.sprite.GetInstanceID()));
#endif
}
}
When I run the script, the field fills in correctly, but the scene file remains unchanged so the field is empty when I reopen the project. Any ideas on how to get this to work the way I want?
Thanks, Chris
Comment
Best Answer
Answer by cgbrown-mos · Dec 05, 2017 at 10:52 PM
Figured it out, had to mark the scene as dirty:
[ContextMenu("Rename With File Extension")]
private void RenameWithFileExtension()
{
#if UNITY_EDITOR
uiImage = gameObject.GetComponent<Image>();
fileName = Path.GetFileName(AssetDatabase.GetAssetPath(uiImage.sprite.GetInstanceID()));
UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(gameObject.scene);
#endif
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612144041im_/https://answers.unity.com/themes/thub/images/avi.jpg)