- Home /
Object in front of character
How can I make sure that when my character is in front of an object it is visible and when it is behind an object it does not "step" on it?! Like my character does in the image.
Answer by lucaswart207 · Mar 04 at 01:08 PM
try to use triggers for each side with this kind of code: using UnityEngine; using System.Collections;
public class SortingOrderScript : MonoBehaviour
{
public const string LAYER_NAME = "TopLayer";
public int sortingOrder = 0;
private SpriteRenderer sprite;
void Start()
{
sprite = GetComponent<SpriteRenderer>();
if (sprite)
{
sprite.sortingOrder = sortingOrder;
sprite.sortingLayerName = LAYER_NAME;
}
}
}
hope it helps :D
Were do I put this, on the character or the objects? And the sorting layer shall be greater than the sorting layer of the objects? I'm somehow new to Unity and I want to learn new things :D
put this script on a gameobject or the barrel make sure to give it a 2d trigger
public class SortingOrderScript : MonoBehaviour { public const string LAYER_NAME = "TopLayer"; public int highsortingOrder = 0; //put the minumum layer value to just get above the player public int lowsortingOrder = 0; //put the normal value here private SpriteRenderer sprite; //this is where it will store the barrels sprite renderer public GameObject barrel; //this is where you put the barrel form your image
void Start()
{
sprite = barrel.GetComponent<SpriteRenderer>();
}
private void OnTriggerEnter2D(Collider2D collision)
{
sprite.sortingOrder = highsortingOrder;
}
private void OnTriggerStay2D(Collider2D collision)
{
sprite.sortingOrder = highsortingOrder;
}
private void OnTriggerExit2D(Collider2D collision)
{
sprite.sortingOrder = lowsortingOrder;
}
//please sub to my youtube https://www.youtube.com/channel/UCI1VlShOOauS2hsHuB9j3PQ
// i hope this works for your intentions
}