- Home /
How can i give time to execute the change of a sprite in my script?
Hi guys, I'm kind of new in Unity2D and I´m doing my first videogame. Im have a question about my script. At this moment my script are changing the sprite of my player when he collides with other sprite. How can i stop my game and give a few seconds to then change the sprite? This is because i want to make a light animation between the change of the script.
Thanks a lot!
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Destroy : MonoBehaviour { public Sprite sprite2; public SpriteRenderer spriteRenderer; private void OnCollisionEnter2D(Collision2D collision) { if (collision.gameObject.tag == "Polen") { spriteRenderer.sprite = sprite2; Destroy(collision.gameObject); } } }
Answer by sean244 · Feb 08, 2019 at 12:45 AM
Try this
using System.Collections;
using UnityEngine;
public class Destroy : MonoBehaviour
{
public Sprite sprite2;
public SpriteRenderer spriteRenderer;
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Polen")
{
//Here, I set it to wait 5 seconds before changing the sprite, but you can change that to any amount of time you want.
StartCoroutine(ChangeSprite(5));
Destroy(collision.gameObject);
}
}
IEnumerator ChangeSprite(float delay)
{
yield return new WaitForSeconds(delay);
spriteRenderer.sprite = sprite2;
}
}
Thank you so much Sean!!! It works amazing. I didn't know how to use the Coroutine in c#
Yea, they're awesome. I use them all the time :) Be sure to subscribe to my YouTube channel https://www.youtube.com/channel/UCo_3O$$anonymous$$EZQiRLQihycbkYd_Q
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Cinemachine follow Player but also focus on trajectory 0 Answers
How do I make sprite renderer's sprite change in runtime c#? 0 Answers
Brackeys EnemyAi Script 0 Answers