Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

unity3d - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...