- Home /
Question by
studioglitch · Sep 24, 2017 at 05:10 PM ·
gameobjectspritetransform.positionrange
How can i change the sprite of my gameobject when it's located within a specific range
So i've made this code where i tried to change the sprite of my gameobject when it hits a specific range of x value but for some reason it doesn't work :/
if(transform.position.x > 2.8f && transform.position.x < 1.12f)
{
GameObject.FindWithTag("Rocket").GetComponent<SpriteRenderer>().sprite = RocketLeft2;
}
if (transform.position.x > -1.12f && transform.position.x < -0.5f)
{
GameObject.FindWithTag("Rocket").GetComponent<SpriteRenderer>().sprite = RocketLeft1;
}
if (transform.position.x > 0.5f && transform.position.x < 0.5f)
{
GameObject.FindWithTag("Rocket").GetComponent<SpriteRenderer>().sprite = RocketNormal;
}
if (transform.position.x > 0.5f && transform.position.x < 1.12f)
{
GameObject.FindWithTag("Rocket").GetComponent<SpriteRenderer>().sprite = RocketLeft1;
}
if (transform.position.x > 1.12f && transform.position.x < 2.8f)
{
GameObject.FindWithTag("Rocket").GetComponent<SpriteRenderer>().sprite = RocketLeft1;
}
Comment
Answer by Thaun_ · Sep 24, 2017 at 05:29 PM
This should work, Try to move the object where the scripts contains in that place (World Space). But, if you have something like in as a child you would need to use transform.localPosition.x instead.
Is this on the Update()? If not, put it there and test it.
The GameObject might not have been found, so maby get a reference of the object first before you use the tag. public SpriteRenderer RocketSpriteRenderer;
Line 9 is useless, cause it Checks if its lower, and if its higher than 0.5f which cannot be done.
Your answer