Hello, I need a block to change sprite when it has nothing above it. (Dirt Sprite to Grass Sprite)
What I did was add a BoxCollider2D as a trigger above the block to detect when one block is on top of the other. But this did not work.
This is my code:
public class SpreadGrassCalculator : MonoBehaviour
{
SpriteRenderer spriteRenderer;
public Sprite dirt;
public Sprite grass;
bool spreadGrass;
void Start()
{
spriteRenderer = GetComponent<SpriteRenderer>();
}
void Update()
{
if (spreadGrass)
spriteRenderer.sprite = grass;
else
spriteRenderer.sprite = dirt;
}
void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.tag == "Blocks")
{
spreadGrass = false;
}
}
}
Are you expecting the state to change fairly often? Update might not be the best method to use here. IF you are going to use Triggers then you may need to write TriggerEnter and a TriggerExit (I’m assuming it’s possible for the state to change during the course of the game.
void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.tag == "Blocks")
{
spriteRender.sprite = grass;
} else {
spriteRender.sprite = dirt;
}
}
I would probably opt for a physics raycast instead, something like this… and I probably wouldn’t call it all the time on every object as that wouldn’t be performant. The TestPosition below would probably be equal to tranform.position + new Vector2(0,1) (or something to get it above the game object)
void CheckGround()
{
Vector2 TestPosition = new Vector2();
float Distance = 0.1f;
Collider2D[] Results = Physics2D.OverlapCircleAll(TestPosition, Distance);
if(Results.Length>0)
{
if (Results[0].gameObject.tag == "Blocks")
{
spriteRender.sprite = grass;
} else
{
spriteRender.sprite = dirt;
}
}
}