Sprite not attaching when creating prefab from script

Hi,
My goal is to create a new Prefab and add a SpriteRenderer to the root game object.

I create an empty game object, add a sprite renderer to it and attach a sprite:

GameObject root = new GameObject(“AtlasRoot”);
SpriteRenderer spriteRenderer = root.AddComponent() as SpriteRenderer;

var spriteRendererComponent = root.GetComponent();

spriteRendererComponent.sprite = (UnityEngine.Sprite)AssetDatabase.LoadAssetAtPath(“Path to file”, typeof(UnityEngine.Sprite));

PrefabUtility.SaveAsPrefabAssetAndConnect(root, “Path to save prefab”, InteractionMode.AutomatedAction);

PrefabUtility.UnloadPrefabContents(root);

The prefab is created but the sprite property is set to ‘None’ for the sprite renderer.

What can be the reason for this?

Hi,

You are adding a SpriteRenderer to the root GameObject, and then you try to get it from the go GameObject.

Hi, I copied the wrong code in the post. I have fixed that.