- Home /
How to change sprite only on click or during shoot state?
So I have a walking/idle sprite and a shooting sprite. When I call the shoot function I want the sprite to change to the shooting one but after it has finished shooting go back to the idle sprite.
This is what I have come up with:
private Sprite[] shootSprite;
// Use this for initialization
void Start()
{
shootSprite = Resources.LoadAll<Sprite>("spritesheet_characters");
}
// Update is called once per frame
void Update()
{
if (fireRate == 0) //if single burst fire
{
if (Input.GetMouseButtonDown(0)) //set Fire1 in input manager
{
Shoot();
}
}
else
{
if (Input.GetMouseButtonDown(0) && Time.time > timeToFire)
{
timeToFire = Time.time + 1 / fireRate;
Shoot();
}
}
}
void Shoot()
{
gameObject.GetComponent<SpriteRenderer>().sprite = shootSprite[15];
//rest of code related to shooting.
}
Now the problem is that once I click it goes to shooting sprite and then stays there, it should go back to previous sprite.
I tried putting:
gameObject.GetComponent<SpriteRenderer>().sprite = shootSprite[39]; //idle sprite
within Update()
but that does not work well as the transition is very fast and very rarely do I see the sprite change during shooting.
Also I dont want to be changing sprite every update as I am using an animator to rotate it while walking.
Is there any way to do this?
Thanks
Answer by Ratslayer · Oct 19, 2017 at 10:01 PM
You have to put the idle sprite line in an else at the end of every if that has Shoot().
if (fireRate == 0) //if single burst fire
{
if (Input.GetMouseButtonDown(0)) //set Fire1 in input manager
{
Shoot();
}
else
{
gameObject.GetComponent<SpriteRenderer>().sprite = shootSprite[39]; //idle sprite
}
}
else
{
if (Input.GetMouseButtonDown(0) && Time.time > timeToFire)
{
timeToFire = Time.time + 1 / fireRate;
Shoot();
}
else
{
gameObject.GetComponent<SpriteRenderer>().sprite = shootSprite[39]; //idle sprite
}
}
Also, you need to refactor your if/elses, there is way too many of them. I don't see a reason for you to call Shoot() more than once in your code, IMHO.
And I would look into mechanim, stuff like changing sprite states is better handled by state machines.
Thank you, and yes you are right it is much easier to do this using the mechanim. Thats how I ended up going with
Your answer
Follow this Question
Related Questions
Unity2D Sprite Fading Issues 1 Answer
convert unity versions, 0 Answers
Change sprite at runtime 1 Answer
check the presence of desired sprite in canvas on click? 0 Answers
How can i change the sprite image of button in run time of a 2d game 1 Answer