Change sprite onTriggerEnter2D
Hey,
I want the sprite to change to another sprite when the player enters the 2D collider. When the player enters the collider I want the sprite to change and when it exits the collider I want the sprite to change back to the original and so on.
Here is my code so far but I can't seem to get it working. If I put a Debug.Log("change_Sprite"); it will show up in the console but the sprite does not change.
Any help would be appreciated. Thank you.
public Sprite mySprite1; public Sprite mySprite2;
private SpriteRenderer spriteRenderer;
void Start () {
spriteRenderer = GetComponent<SpriteRenderer>();
if (spriteRenderer.sprite == null)
spriteRenderer.sprite = mySprite1;
}
void OnTriggeEnter2D (Collider2D other){
if (other.GetComponent<Collider2D> ().gameObject.tag == "_mySprite") {
ChangeTheSprite ();
}
}
void OnTriggerExit2D ( Collider2D other ){
if (other.GetComponent<Collider2D> ().gameObject.tag == "_mySprite") {
ChangeTheSprite ();
}
}
void ChangeTheSprite ()
{
if (spriteRenderer.sprite == mySprite1)
{
spriteRenderer.sprite = mySprite2;
}
else
{
spriteRenderer.sprite = mySprite1;
}
}
}
Your answer
Follow this Question
Related Questions
Sprites being skipped in sprite change script 0 Answers
Sprites Pink After Upgrading Unity 1 Answer
Getting name of Spritesheet on runtime with C#? (Not individual SpriteName) 1 Answer
Problem Changing Sprites with an Array of Sprites 1 Answer
Ordering my multi layered sprite characters (2D, Isometric) by the z Axis 0 Answers