- Home /
Changing sprites from spritesheet on collision. What am I doing wrong?
My code is listed below in a pastebin link. I've tried my best, but I just can't seem to do it.
I'm trying to get a block to switch to a different sprite every time it is collided with, and finally be destroyed. I just... Can't seem to get it working when I have switched to a sprite sheet. Help please :)
I have not worked with sprites too much but i'm sure that following these steps you will be able to debug your code:
$$anonymous$$ake sure that the "OnCollisionEnter2D(Collision2D col)" function is called, maybe something on the colliders was not set up correctly. You can do that by simply calling "debug.log" inside that function and look if it is printed correctly.
If the function is called then the next problem might be the line "if (this.gameObject.GetComponent().sprite == redblock)", make sure that this line is working correctly (to me it seems a bit odd) if not look up some documentation about sprites, you could start here and it should not take you too long to solve (or you could just google it). You can check that placing the debug.log inside the if statement.
In case everything else works the mistake must be in the line "this.gameObject.GetComponent().sprite = yellowblock;" and again, look up the unity documentation about sprites and how to assign them.
Good luck and let me know if that helps!
Answer by JoJoJet · Jul 13, 2015 at 11:11 AM
I completely re-wrote your script, making it less complicated and fixing your problem:
using UnityEngine;
using System.Collections;
public class block : MonoBehaviour {
public Sprite[] blockColors; //Assign the length of the array in the inspector,
//and drag the sprites you want it to change to into each element.
public int currentSprite = -1; //The int that tells us which sprite in the array
//we will use.
public bool deleting; //Unity doesn't actually delete an object until the next
//frame, so this will allow us to make sure the code doesn't break by having
//currentSprite be longer than the array length.
private int arrayLength;
void Start() {
arrayLength = blockColors.Length - 1;
}
void OnCollisionEnter2D() {
currentSprite += 1; // adds 1 to the "currentSprite" integer.
if (currentSprite > arrayLength) { //Deletes the object if currentSprite is greater than the
//length of the blockColors array
deleting = true;
GameObject.Destroy (gameObject);
}
if (!deleting) {
GetComponent<SpriteRenderer> ().sprite = blockColors [currentSprite]; //sets the SpriteRenderer's
//Sprite to be the desired sprite in the blockColors array.
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220611230917im_/https://answers.unity.com/themes/thub/images/avi.jpg)