FernandoRosa
FernandoRosa

Reputation: 101

Unity 2D C# Instantiate sprite on canvas. Can't find what's wrong

I read many questions about this, but I still can't find what my problem is... I'm trying to instantiate a prefab at the canvas. It is compose of a button and a sprite. The button looks ok, but the sprite is not visible at the Game (but is visible at the Scene).

I'm doing something wrong, but I can't see what...

 [SerializeField] GameObject finishedLevel;

     private void Start()
 {
     finishedLevel = Instantiate(finishedLevel, transform.position, transform.rotation);
     finishedLevel.transform.SetParent(GameObject.FindGameObjectWithTag("Canvas").transform, false);

 }

enter image description here

Upvotes: 2

Views: 6250

Answers (1)

Programmer
Programmer

Reputation: 125275

SpriteRenderer is not made to be used with the Canvas. You are confusing and misusing the two.

SpriteRenderer is used for displaying 2D Objects like a 2D animated character or a 2D environment. You can attach Rigidbody2D and Colliders to SpriteRenderer.

Canvas is used for UI display only. It is used for displaying things such as UI texts, buttons, sliders, scrollbars and images. You shouldn't attach Rigidbody2D and Colliders to it or its child objects.

With the explanation above, you should be able to determine which one to use. If you just need to display image under a Canvas, use the Image, or RawImage component since they are part of the UI system. This should work but do not make SpriteRenderer a child of a Canvas. If you have to use SpriteRenderer, make it its own object or under another object but it should not be under a Canvas. You may find Unity's UI tutorial useful.

Upvotes: 9

Related Questions