How to load and render a sprite in script?

Hi folks,

I’ve just come over from XNA and wish to port one of my 2D projects onto Unity. I found this article from a former XNA-er which suggested creating a script which instantiates the XNA game class and acts as a proxy between it and Unity. While I appreciate the limitations of this technique, it interests me enough to give it a shot.

XNA provides a SpriteBatch class for sprite rendering, but the article above suggests using a custom mesh in Unity. I’ve tried and failed to get this to work. I’ve included my code below, which throws a NullReferenceException in the material constructor. I’m very lost, and would appreciate any insights you can offer.

Apologies for the newbie question!

Cheers!

using UnityEngine;

public class GameManager : MonoBehaviour
{
	Mesh mesh;
	Shader shader;
	Material material;

	// Start
	void Start()
	{
		mesh = new Mesh();
		shader = new Shader();
		material = new Material(shader);
		material.mainTexture = Resources.Load("Content/Texture") as Texture;    
	}
	
	// Update
	void Update()
	{
		Vector3[] vertices = new Vector3[4];
		vertices[0] = new Vector3(540, 260, 0);
		vertices[1] = new Vector3(740, 260, 0);
		vertices[2] = new Vector3(540, 460, 0);
		vertices[3] = new Vector3(740, 460, 0);

		Vector2[] uvs = new Vector2[4];
		uvs[0] = new Vector2(0, 0);
		uvs[1] = new Vector2(0, 0);
		uvs[2] = new Vector2(0, 0);
		uvs[3] = new Vector2(0, 0);

		int[] triangles = new int[6];
		triangles[0] = 0;
		triangles[1] = 1;
		triangles[2] = 2;
		triangles[3] = 2;
		triangles[4] = 1;
		triangles[5] = 3;
		
		mesh.vertices = vertices;
		mesh.triangles = triangles;
		mesh.uv = uvs;
		
		Graphics.DrawMesh(mesh, Matrix4x4.identity, material, 0);
	}
}

You can’t really instantiate a shader like that, have a look at this: Shader.Find

Also, you should put the mesh construction code in the Start function – Update is called every frame, and you probably don’t need to regenerate it so often. The UV’s are off, too (they’re all zeroed out).