IObjectResolver.Instantiate() makes prefab dirty.
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
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;
}
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.
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
I created a PR using @AlonTalmi's idea.