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!

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: