- Home /
The question is answered, right answer was accepted
Sprite Flip Towards Camera
Concept is simple, character turns around based on which side of the screen the mouse is on. The script is:
void Update () { var MousePosition = Input.mousePosition; var PlayerPosition = Camera.main.WorldToScreenPoint(transform.position); if (MousePosition.x < PlayerPosition.x) { SpriteRenderer.flipX = true; }
if (MousePosition.x > PlayerPosition.x)
{
SpriteRenderer.flipX = false;
}
}
I'm getting the error "CS0120: An object reference is required to access non-static member 'UnityEngine.SpriteRender.flipX"
I don't know exactly what I've done wrong. If sprite render flip is a static variable, how would I edit it? Or is something else a static variable? I'm not sure really, var is still somewhat confusing to me.
Thanks for any help!
Answer by ElijahShadbolt · Feb 15, 2018 at 06:36 AM
Note that SpriteRenderer.flipX is not static, which means you need to call flipX from an instance of the SpriteRenderer class. Your GameObject has a SpriteRenderer component attached (which is an instance of the class SpriteRenderer, not the static class itself). You could use the following code to fix the error.
Replace
SpriteRenderer.flipX = false;
with
SpriteRenderer sr = this.GetComponent<SpriteRenderer>();
sr.flipX = false;
See also:
Thanks! I actually managed to narrow that down to just { this.GetComponent().flipX = false; } Thanks for the assistance! I still had a narrow understanding of the "this" and "getcomponent" commands but I think I understand them now. Thank you!
Follow this Question
Related Questions
Flipping a group of sprites 1 Answer
flip sprite while using mathf.sin 0 Answers
Angles invert after flipping player by 180 on Y-axis in 2D. 0 Answers
Flip sprites in enemy spawner 1 Answer
Teleport wrapping effect/Mask 0 Answers