VContainer icon indicating copy to clipboard operation
VContainer copied to clipboard

IObjectResolver.Instantiate() makes prefab dirty.

Open yellowisher opened this issue 1 year ago • 1 comments

If I instantiate prefab with IObjectResolver.Instantiate(), the prefab show up in my VCS without any changes. Yes, when I stage them, they are gone but its pretty annoying.

The reason is IObjectResolver.Instantiate() directly disable the prefab itself then Instantiate it. (maybe for calling Inject before Awake?) Zenject Instantiate a prefab as a child of inactive GameObject rather than disable prefab itself. Link

yellowisher avatar Apr 28 '24 07:04 yellowisher

public static GameObject InstantiateAndInject([NotNull] this IObjectResolver resolver, [NotNull] GameObject prefab, Transform parent = null)
        {
            if (prefab == null)
                throw new NullReferenceException(nameof(prefab));
            
            bool prefabWasActive = prefab.activeSelf;
            prefab.SetActive(false);
            GameObject instance = resolver.Instantiate(prefab, parent);
            prefab.SetActive(prefabWasActive);
            instance.SetActive(prefabWasActive);
            return instance;
        }

IaroslavGusiev avatar May 11 '24 10:05 IaroslavGusiev

I would like to bump this one! It caused issues when I used RegisterComponentInNewPrefab to instantiate a prefab in a package that is included via the Unity Package Manager. All package files are read only, so every time the project was run in Editor, the prefab was marked as dirty and threw errors when saving the project.

Harriet92 avatar Nov 06 '24 11:11 Harriet92

I think a better, and simpler approach will be to get the prefab's initial dirty state using EditorUtility.IsDirty and if it's not, clear the flag later using EditorUtility.ClearDirty

That way we don't need to create a temporary parent and changing the parent later

AlonTalmi avatar Nov 06 '24 11:11 AlonTalmi

I created a PR using @AlonTalmi's idea.

yellowisher avatar Nov 09 '24 13:11 yellowisher