Sprite.Create alpha
Can anybody tell me why created sprites are translucent?
void Start ()
{
Texture2D texture = new Texture2D(32, 16);
spriteRenderer.sprite = Sprite.Create(texture, new Rect(0.0f, 0.0f, texture.width, texture.height), new Vector2(0.5f, 0.5f), 4.0f);
}
White sprite has a higher render order and has an alpha of 1 yet we can see through it?
Answer by TBruce · Dec 23, 2016 at 08:57 PM
This is the default way textures are created - see the docs.
As the docs state
Usually you will want to set the colors of the texture after creating it, using SetPixel, SetPixels and Apply functions
Check out this modification to your script
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class SpriteManager : MonoBehaviour
{
public SpriteRenderer spriteRenderer;
public Color defaultColor = Color.white;
void Start ()
{
if (spriteRenderer != null)
{
Texture2D texture = new Texture2D(32, 16);
List<Color> cols = new List<Color>();
for (int i = 0; i < (32 * 16); i ++)
{
cols.Add(defaultColor);
}
texture.SetPixels(cols.ToArray());
texture.Apply();
spriteRenderer.sprite = Sprite.Create(texture, new Rect(0.0f, 0.0f, texture.width, texture.height), new Vector2(0.5f, 0.5f), 4.0f);
}
}
}
That worked, however it didn't give me the results that i expected, it does when i use my own sprite and use SetPixel on it, however the changes to that sprite are permanent, how can i create a clone of that sprite on Start and set the pixels of that clone ins$$anonymous$$d?
Hi $$anonymous$$henaB, This can be done with a slight modification to the above script
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Sprite$$anonymous$$anager : $$anonymous$$onoBehaviour
{
public SpriteRenderer spriteRenderer;
public Sprite sprite; // sprite to copy
void Start ()
{
if ((spriteRenderer != null) && (sprite != null))
{
Texture2D texture = new Texture2D(sprite.texture.width, sprite.texture.height);
texture.SetPixels(sprite.texture.GetPixels());
texture.Apply();
spriteRenderer.sprite = Sprite.Create(texture, new Rect(0.0f, 0.0f, texture.width, texture.height), new Vector2(0.5f, 0.5f), 4.0f); // you may want to change or even remove the last parameter of Sprite.Create()
}
}
}
This requires however that you change the Texture Type
of your sprite to Advanced
and then check the Read/Write Enabled
check box (don't forget to hit apply).
Thanks, however i get the same result than with the previous solution, here's a comparison of when i set the pixel at 0,0 of the sprite directly, and if i create a sprite and use a Texture2D. With the Texture2D the green pixel is blurry. Could this have anything to do with filtering?