Assigning fields using editor scripts does not trigger project changed, and as such cant be saved!

VERSION 2021.3.21f1

Using an editor script to change fields of many scripts at the same time does not create the little asterisk (*), that signals that there were changes made to the project.

Because of this, if you close unity and reopen it, all the fields you changed are back to null

Even manually saving the scene + saving the project wont solve it, if you close unity you still lose your changes.

IF YOU ENTER PLAYMODE, THE FIELDS WILL BEHAVE AS SET.

BUT IF YOU BUILD THE GAME, IT WILL BEHAVE AS THE FIELDS WERE NULL!!!!

FIX I FOUND: create an empty object and delete it. This will trigger the asterisk *, and now you can save.

Steps to reproduce from a clean project: (3 scripts), (2objects)

Editor script:

using UnityEditor;
using UnityEngine;

public static class IterateHierarchy
{
    [MenuItem("EditorMenu/IterateHierarchy")]
    static void Editor_IterateHierarchy()
    {
        _AssignedComponentScript scriptToAssign = GameObject.Find("AssignFromThisObject").GetComponent<_AssignedComponentScript>();


        foreach (Transform obj in UnityEngine.Object.FindObjectsOfType<Transform>(includeInactive: true))
        {


            _ReceiverComponentScript receiver = obj.GetComponent<_ReceiverComponentScript>();

            if (receiver != null)
            {


                receiver.script = scriptToAssign;


            }

        }


    }

}

script 1:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class _AssignedComponentScript : MonoBehaviour
{
    public int a;
}

script 2:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class _ReceiverComponentScript : MonoBehaviour
{

    public _AssignedComponentScript script;
}

object setup + steps to reproduce:

9648680--1372553--Untitled.png

WORKAROUND: After step 5, create empty object, delete empty object, save. And its fixed.

It's not a bug. Whenever you modify an object via code you need to tell Unity that something has changed.

You can do this by 'dirtying' the object. Usually with UnityEditor.EditorUtility.SetDirty(): https://docs.unity3d.com/ScriptReference/EditorUtility.SetDirty.html

1 Like