Search Unity

how to Pass Sprite to SpriteRenderer in OnPostprocessSprites() Event?!

Discussion in 'Scripting' started by MrjmCyberman, Nov 21, 2017.

  1. MrjmCyberman

    MrjmCyberman

    Joined:
    Nov 3, 2017
    Posts:
    2
    after importing sprites inside unity , i want to make a Prefab out Of them and assign them a SpriteRenderer and BoxCollider2D component , all automaticly.
    every thing is good exept i cant pass the imported Sprite to the SpriteRenderer component any how.
    i dont knoow what im missing here. any help will be appritiated.


    Code (CSharp):
    1.  void OnPostprocessSprites(Texture2D texture, Sprite[] sprites)
    2.        {
    3.          
    4.         Sprite sp = sprites[0];
    5.             TextureImporter importer = (TextureImporter)assetImporter;
    6.             importer.textureType = TextureImporterType.Sprite;
    7.  
    8.             GameObject GO = new GameObject();
    9.            GO.name = sp.name;
    10.             GO.AddComponent<SpriteRenderer>().sprite = sp;// not works
    11.             GO.AddComponent<SpriteRenderer>().sprite = (Sprite)Resources.Load(importer.assetPath);// not works
    12.  
    13.             GO.AddComponent<BoxCollider2D>();
    14.  
    15.             Object prefab = PrefabUtility.CreateEmptyPrefab(string.Format("Assets/Resources/X_Temp/{0}.prefab", GO.name));
    16.            if (prefab != null)PrefabUtility.ReplacePrefab(GO, prefab, ReplacePrefabOptions.ConnectToPrefab);
    17.  
    18.         }
    19.  
    there is no Error or messages , it makes the prefab with BoxCollider And SpriteRendere Components But SpriteRenderer's Sprite Field Has No Sprite, and set to none.

    how can i fix this?
     
    Last edited: Nov 22, 2017
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,751
    Please add code formatting tags to make your code more readable.

    Also, after this line:

    Code (csharp):
    1. Sprite sp = sprites[0];
    Insert a line that says:

    Code (csharp):
    1. Debug.Log( "Sprite = " + sp.ToString());
    And see if it prints the name of the sprite or not. That will identify if the problem is inside this block of code or external to it, in the code that sets up the array of sprites.
     
  3. MrjmCyberman

    MrjmCyberman

    Joined:
    Nov 3, 2017
    Posts:
    2
    yes it returns the name of imported sprite.
    and this :
    Code (CSharp):
    1. importer.assetPath
    returns the imported path+name of sprite correctlly.
     
    Last edited: Nov 22, 2017
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,751
    I will assume that the duplication of Line 10 and line 11 is intentional to show the two approaches you tried?