aeee98
aeee98

Reputation: 114

Sprite disappearing to the back of another sprite on moving to defined point via transform.position

I have a difficulty with Unity2D's Sprite rendering.

Currently I have a sprite for a gameBoard, an empty GameObject holding the spawnPoint, a random sprite marking it, as well as a playerSprite to be instantiated as a prefab. If I am just using the hierarchy on Unity, the playerSprite shows perfectly above the gameBoard, and "hard-coding" its position will always keep it above the gameBoard sprite, visible to the eye.

The problem comes when I want to instantiate the gameBoard and dynamically adding the playerPrefabs into the game.

Here is the current code snippet I am currently using:

gameBoard.SetActive(true); //gameBoard is defined as a public gameObject with its element defined in Unity as the gameBoard sprite. 
Player.playerSprite = (GameObject)Instantiate(Resources.Load("playerSprite"));
Player.playerSprite.transform.localPosition = spawnPoint.transform.localPosition;

The result is that the spritePrefab spawns at the place I want perfectly, but behind the gameBoard sprite, making it hidden when the game runs.

The result is the same when using transform.position instead of transform.localPosition

How should I code the transform part. such that I can still make my playerSprite visible? Thanks.

Upvotes: 0

Views: 924

Answers (1)

Venkat at Axiom Studios
Venkat at Axiom Studios

Reputation: 2516

It's most likely not an issue with the position, but rather the Sorting Order of your Sprite Renderers.

The default values for any SpriteRenderer is Layer = Default & Sorting Order = 0

Sprite Renderers with a higher sorting order are rendered on top of those with a lower value.

Add the following lines to the end of your code, and try it out.

gameBoard.GetComponent<SpriteRenderer>().sortingOrder = 0;
Player.playerSprite.GetComponent<SpriteRenderer>().sortingOrder = 0;

Obviously, you could do the same thing in the inspector as well.

Upvotes: 2

Related Questions