Scripted Sprite isnt shown

Hey there !

I tried to create a Sprite using a C# Script. It should be displayed on the middle of the Screen. But it just dont show up. Any ideas ?

My camera position is : 0f,0f,-2.5f

public Texture2D tex;
public Sprite mySprite;
public SpriteRenderer sr;


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);

}

void OnGUI(){

if (GUI.Button(new Rect(10, 10, 100, 30), "Add sprite"))
{
sr.sprite = mySprite;
sr.transform.position = new Vector3(0, 0, -2.2f);

}

}

Any ideas ?

Is my question so bad, or why dont anyone answer me ? :smile:

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:

transform.position = new Vector3(0, 0, -2.2f);

transform is just shorthand for :

Transform transform = GetComponent<Transform>();
1 Like

Great ! Thanks that works ! :smile: you saved my life ! ^^