I have been making a small game (like walking trough corridor and shooting to enemies) and I used Collisions to make enemies change their color. But OnCollisionExit2D won’t work.
Here is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class zombieBehaviour : MonoBehaviour
{
public int HP = 3;
public Sprite[] sprites;
private SpriteRenderer spriteRend;
public bool Hit = false;
void Start()
{
spriteRend = GetComponent<SpriteRenderer>();
}
void Update()
{
if(Hit==false)
{
spriteRend.sprite = sprites[0];
}
else
{
spriteRend.sprite = sprites[1];
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if(collision.gameObject.tag == "Bullet")
{
Hit = true;
}
}
private void OnCollisionExit2D(Collision2D collision)
{
if(collision.gameObject.tag == "Bullet")
{
Hit = false;
}
}
}
If there is some stupid mistake, sorry for it. I’m new to unity.
When bullet dissapears (wich works fine) the "Hit’ variable won’t change back to false and the sprite will remain “sprites[1]”
So first off, the way you do things in update shouldnt be done as it will set that every frame and perform the if check every frame. You dont even need to, why not do this:
using System.Collections.Generic;
using UnityEngine;
public class zombieBehaviour : MonoBehaviour
{
public int HP = 3;
public Sprite[] sprites;
private SpriteRenderer spriteRend;
void Start()
{
spriteRend = GetComponent<SpriteRenderer>();
}
private void OnCollisionEnter2D(Collision2D collision)
{
if(collision.gameObject.tag == "Bullet")
{
spriteRend.sprite = sprites[0];
}
}
private void OnCollisionExit2D(Collision2D collision)
{
if(collision.gameObject.tag == "Bullet")
{
spriteRend.sprite = sprites[1];
}
}
}
That way you dont need update at all, and you dont need the Hit variable meaning it is more efficient.
Try that and tell me if its still not working? if it is not, then it means possibly you are triggering an oncollisionenter2d again after it exits, and we may need to see the scene setup itself to troubleshoot that.
As suggested, you should make sure it’s actually called, because it could be that enter is called again if the objects collides multiple times with the other object.
Add a simple Debug.Log or attach the debugger and check whether the engine calls that piece of code, and how often it calls it.