How do I make item pickup change sprite on collision?
Hello there! this is my first question here and I'm a total newbie. I have made an item that can be picked up by the player on collision and it simply resets the player animation (not my point here) and I just wanted the sprite of the pickup to change before it destroys itself.
I have searched around but I couldn't find anything for this.
Here's my current code on the pickup:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class PickUpReCharge : MonoBehaviour {
public Animator anim;
public Animator animc;
void Start()
{
}
void Update()
{
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
anim.Rebind();
animc.Rebind();
Destroy(gameObject);
}
} }
Everything works fine, but when I tried to use something like transitioning to a different animation state where the pickup animation occurs, the object destroys itself before the animation plays and just doesn't look right.
This is what I tried to do first:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class PickUpReCharge : MonoBehaviour {
public Animator anim;
public Animator animc;
public Animator animp;
void Start()
{
}
void Update()
{
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
anim.Rebind();
animc.Rebind();
animp.Play("Pickup", 0, 0.0f);
Destroy(gameObject);
}
} }
But it didn't work at all.
I'm looking for an effect kind of like when sparkles appear after you pick up a coin for example.
Is there any premade asset that I can reference from maybe? Or is the code an easy one and I'm just that bad at coding lol?
Thanks ^^
Answer by xxmariofer · Apr 16, 2019 at 04:41 PM
try this, just assign the sprite in the inspector
public Sprite yourNewSprite;
private IEnumerator OnTriggerEnter2D(Collider2D collision)
{
if (other.tag == "Player")
{
anim.Rebind();
animc.Rebind();
//do your stuff here like changing the sprite
GetComponent<SpriteRenderer>().sprite = yourNewSprite;
yield return new WaitForSeconds(3.0f);//will wait for 3 secs
Destroy(gameObject);
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612195602im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
2D Shooter Make Item Pickup Change Bullet Prefab On Collision 1 Answer
Collision Detection between two different Prefabs doesnt work 1 Answer
If Statement not working properly - Comparing game objects 0 Answers
Game Objects wont appear after restart 0 Answers
how do i collide and kill the enemy while pressing space Unity 5 C# 2 Answers