Its because you don’t have a SpriteRenderer component on your GameObject. This line here:
public SpriteRenderer sr;
is just a placeholder for an actual object (which you haven’t created yet). Add this line to start:
void Start () {
tex = (Texture2D)Resources.Load<Texture2D>("Sprites/ButtonAcceleratorUpSprite");
tex.Apply();
mySprite = Sprite.Create(tex, new Rect(0.0f, 0.0f, tex.width, tex.height), new Vector2(0.5f, 0.5f), 100.0f);
sr = gameObject.AddComponent<SpriteRenderer>();
}
Also note a GameObject is a container for a bunch of components that make the object what is is. When you create an Empty GameObject a transform component is automatically attached. When you attach your script above thats a component. When we create the SpriteRenderer thats a component. So this line here:
sr.transform.position = new Vector3(0, 0, -2.2f);
Is actually saying find the gameobject sr is attached to, then find the transform component and set its position. So the spriteRenderer itself does not have a transform. Its just a sibling component to the transform. You can simply just do this as well: