I have an object (TestObj) and I want to change its sprite from sprite1 to sprite2 when it’s clicked on. How would I code that in C#?
Place both sprites in the gameobject and then turn them on/off as needed with SetActive();
I’m not entirely sure how to do that.
You want to do this?
public Sprite sprite1, sprite2; // Sprites
private SpriteRenderer spriteRenderer;
void Start () {
spriteRenderer = gameObject.GetComponent<SpriteRenderer> ();
}
void OnMouseDown () {
if (spriteRenderer.sprite == sprite1) {
spriteRenderer.sprite = sprite2;
} else {
spriteRenderer.sprite = sprite1;
}
}
Create a new game object.
Drag your sprites into that gameobject in the hierarchy.
Create a script along these lines:
public class ClickToChange : MonoBehaviour {
public GameObject sprite_1;
public GameObject sprite_2;
void Awake()
{
// just to ensure a clean start.
sprite_1.SetActive(true);
sprite_2.SetActive(false);
}
void OnMouseDown()
{
sprite_2.SetActive(!sprite_2.activeSelf);
sprite_1.SetActive(!sprite_1.activeSelf);
}
}
You can then place your script and collider on that game object, and the add the references in the inspector.
Not very fancy, but will do the trick.
Cheers.
Oh! I completely forgot that I could do that despite doing a tutorial on it whoops
Thanks.