- Home /
Placing the sprite game object in the players position and also enable and disable it when needed
I have a sprite game object in my unity game. It is an animation which is used to show when a collectible is collected by the player. So I need the animation to be played only when the player collects a collectibLe. also the sprite game object has to be positioned in the same position as that of the player. How does I do that? Any help from any one is easily appreciated. Thanks in advance.
Answer by fddefdef · Jan 20, 2015 at 10:28 AM
If i understood correctly your question you just have to write a script that instantiates that sprite you want at the player's position.
I assume that somewhere in your code you have called a collision function to detect when the player has collected the collectible object. Inside that function you could call the Instantiate function and set the position of the sprite at the player's position. To be clear you'll have something like that.
OnCollisionEnter2D(collision2D collision)
{
if(collision.transform.tag == "collectible")
{
your code here
Instantiate(sprite animation, transform.position, Quaternion.identity);
}
}
For the animation to be played only when the sprite appears, just uncheck the loop parameter of the animation from the inspector.
I had written the code for the collision detection and all. I only need to know, how to place the sprite renderer to the players position, since players position is world point and sprite renderer is in 2D. So that when coin collected the sprite animation plays. By the way my game is a 3D game.
Sprite renderer is just a component attached to an object that exists in 3D world space and not in screen space. You just need to set the position of the sprite game object to that of the player.
Answer by shanky_91 · Jan 20, 2015 at 11:44 AM
On a monobehaviour attached to the player use this method:
void OnCollisionEnter(Collision collision) {
if (collision.gameObject.tag == "collectable")
{
//Then create sprite
//Set sprite transform.position to transform.position
}
}
you will also need to add a tag to the collectable called "collectable"
Your answer
Follow this Question
Related Questions
Would changing the sprite need a new set of animation? 0 Answers
Alpha masking multiple 2D Sprite GameObjects with 1 Sprite GameObject 0 Answers
I have an animaiton problem about sprite loading. 0 Answers
how can i get the clicked sprite which is placed on UI canvas? 1 Answer
how can i access multiple sprites using a single variable? 1 Answer