I have been trying to write a method that fills a rectangle with a color. I've tried it as a new 2D and 3D project just in case, but this gives the same results.
Basically, i want the script to make a new GameObject, give it a SpriteRenderer component and then fill the given rectangle with the given color.
I have tried to work from the Unity docs and other sources of info, but no matter how much I look around, this now looks correct to me but doesnt work.
The result (as pictured) shows the new object with the sprite renderer and even shows the right size (there are blue 'corner' icons in the scene view I can see but no sprite or rectangle of any kind.
using UnityEngine;
public class GameBoard : MonoBehaviour
{
const ushort cellCount_x = 10;
const ushort cellCount_y = 24; // only 20 will be visible to player
const ushort cellsize = 50;
GameObject testBlock;
SpriteRenderer testBlockRen;
private void Start()
{
testBlock = new GameObject();
testBlockRen = testBlock.AddComponent<SpriteRenderer>();
testBlockRen.sprite = CreateRectSprite(new Rect(0, 0, cellsize, cellsize), Color.red);
}
Sprite CreateRectSprite(Rect rect, Color color)
{
Texture2D tex = Texture2D.whiteTexture;
tex.SetPixel(0, 0, color);
tex.Resize((int)rect.width, (int)rect.height);
Sprite sprite = Sprite.Create(tex, rect, Vector2.zero);
return sprite;
}
}
By the way: I have made sure the camera 'z' is less than 0 (it's -10). And the camera is centred where the sprite is supposed to appear.
Note: I can get a sprite to render fine if I create a texture in gimp and then use Resources.Load() . But I am trying to create the sprite using no source texture whatsoever (other than Texture2d.whitetexture)