- Home /
Question by
The-Z-axis · Mar 12, 2019 at 02:25 AM ·
layerscomparesorting layers
Compare Z-Axis value of two objects?
So what I want to have happen is I want to change an object's layer based on the value of where it is on the Z-Axis. Right now the placeholder code does this simply by pressing the Q key, but this was just to test if the rest of the code works. The missing piece of the puzzle is replacing " if (Input.GetKey("q")) " with the code that will compare the value of the object with the player object. Any help in this would be immensely appreciated.
using UnityEngine;
using System.Collections;
public class Layering : MonoBehaviour
{
public const string LAYER_NAME = "Default";
public int sortingOrder = 0;
private SpriteRenderer sprite;
void Start()
{
sprite = GetComponent<SpriteRenderer>();
if (sprite)
{
sprite.sortingOrder = sortingOrder;
sprite.sortingLayerName = LAYER_NAME;
}
}
void Update()
{
if (Input.GetKey("q")) //Now if the player's Z-axis value is greater than the current object's...
{
sprite.sortingLayerName = "Back"; //Change the layer to Back
}
else
{
sprite.sortingLayerName = "Default"; //Otherwise change it to Default
}
}
}
Comment
if(playerTransform.position.z > spriteTransform.position.z)//did you test this?
Best Answer
Answer by cs120319992 · Mar 12, 2019 at 08:34 AM
if(Input.GetKeyDown("q")) {
if(player.transform.position.z > object.transform.position.z) {
sprite.sortingLayerName = "Back";
} else {
sprite.sortingLayerName = "Default";
}
}
// or try to change sort index layer
player.GetComponent<SpriteRenderer>(). sortingOrder = (int)player.transform.position.z;
Yes! That's what I needed, I'm still learning a lot of C# syntax, that second line was the final missing piece of the puzzle, thank you so much!