Delay and Misfire of 2D sprite changer script,Delayed sprite change (OnCollisionStay2D)
Hello all. I've been trying to create a simple multi-tier "destruction" script using a sprite changing system for a new prototype I'm working on, rather than using animations which seemed like it could make it more complicated; maybe I was wrong lol. So I have a pretty severe delay in my script firing and actually "changing" to the next sprite. Sometimes it'll seem to be working well for a moment, but then when I "BlowUp" a fresh building after hitting another one, it skips right over to the second or third "dmgSprite." I've tried using triggers instead of just collisions, I've messed with the rigidbodies a lot, I'm at a loss.
They are prefabs because I'm working towards having procedural generation, but I was under the impression that if I attached the script to each building instantiated, that script would run separately for them when called. Otherwise being prefabs I figured putting the script on the player for pressing space would destroy all buildings instantiated. Any ideas how I can make this run more smoothly? I considered putting some kind of check into Update() but I honestly wasn't sure where to start with that.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DestroyObject : MonoBehaviour
{
public Sprite mainSprite;
public Sprite dmgSprite;
public Sprite dmgSprite2;
public Sprite dmgSprite3;
private SpriteRenderer spriteRenderer;
// Use this for initialization
void Start ()
{
spriteRenderer = GetComponent<SpriteRenderer>();
if (spriteRenderer.sprite == null)
spriteRenderer.sprite = mainSprite;
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.name == "Player" && Input.GetKeyDown(KeyCode.Space))
{
BlowUp();
}
}
void BlowUp()
{
if (spriteRenderer.sprite == mainSprite) {
spriteRenderer.sprite = dmgSprite;
}
else if (spriteRenderer.sprite == dmgSprite) {
spriteRenderer.sprite = dmgSprite2;
}
else if (spriteRenderer.sprite == dmgSprite2) {
spriteRenderer.sprite = dmgSprite3;
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612175452im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Instantiated Prefab won't instantiate with a script reference 1 Answer
Help with converting small pseudo script to C# please? 0 Answers
PrefabUtility.RevertPrefabInstance() not working 2 Answers
Make a game object face another game object when instantiated 2 Answers
How can I in-script create gameobject from prefab? 2 Answers