- Home /
Changing SpriteRenderer order in script
Hello, I have a 2D game where you can shoot arrows, I want to make it so each time the arrow prefab is instantiated, the sorting order is randomized so 50% of the time the arrow appears in front of the player sorting layer and 50% behind. I'm not using any tutorial on this and just shooting in the dark
Here is the code that is on the Bullet prefab
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletProperties : MonoBehaviour
{
SpriteRenderer sp;
void Start()
{
sp.GetComponent<SpriteRenderer>();
int randomNum = Random.Range(1, 10);
Debug.Log(randomNum);
if(randomNum > 5)
{
sp.sortingOrder = 4;
Debug.Log("BULLET SHOULD BE IN BACK");
} else if (randomNum < 5)
{
sp.sortingOrder = 6;
Debug.Log("BULLET SHOULD BE IN FRONT");
} else
{
Debug.Log("It didn't work obviously");
}
}
}
The bullet, from my understanding, gets the sprite renderer by using GetComponent, sets a random number between 1 and 10, and depending on the number will change the sorting order, in the editor, the prefab's order is 0
However, when the game is played and a bullet is shot, it always shows behind the player (Due to the 0 sorting layer before) and I get some strange errors in the editor, the Debug.Log's also do not display anything in the console, as if it doesn't even go through the "if" statement, none of the prefabs in the scene hierarchy have changed either
Screenshot of editor
How would I go about this functionality? I want the bullets to appear on either side of the player at random just for some visual detail
Answer by WinterboltGames · Aug 19, 2020 at 12:09 AM
Change:
sp.GetComponent<SpriteRenderer>();
To:
sp = GetComponent<SpriteRenderer>();