Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Sprite not attaching when creating prefab from script

Discussion in 'Scripting' started by yadu_raj, May 11, 2020.

  1. yadu_raj

    yadu_raj

    Joined:
    Nov 15, 2019
    Posts:
    2
    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<SpriteRenderer>() as SpriteRenderer;

    var spriteRendererComponent = root.GetComponent<SpriteRenderer>();


    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?
     
    Last edited: May 12, 2020
  2. arfish

    arfish

    Joined:
    Jan 28, 2017
    Posts:
    777
    Hi,

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

    yadu_raj

    Joined:
    Nov 15, 2019
    Posts:
    2
    Hi, I copied the wrong code in the post. I have fixed that.