[英]Unity 2D sprite doesn't flip
I'm doing a platformer game with Unity 2D and I wanted to flip the character sprite left when the player move him left, but for some reasons it doesn't work.我正在用 Unity 2D 做一个平台游戏,我想在玩家向左移动角色时向左翻转角色精灵,但由于某些原因它不起作用。 I tried to make this one script:我试图制作这个脚本:
transform.rotation = new Vector3(0f, 180f, 0f);
but it didn't work.但它没有用。 So then I wrote this:然后我写了这个:
transform.localScale = new Vector3(-0.35f, 0.35f, 1f); //the player's scale x and y are 0.35 by default
but it didn't work too.但它也不起作用。 Then I found this error message in the console: NullReferenceException: Object reference not set to an instance of an object UnityEditor.Graphs.Edge.WakeUp () (at C:/buildslave/unity/build/Editor/Graphs/UnityEditor.Graphs/Edge.cs:114) .然后我在控制台中发现了这个错误信息: NullReferenceException: Object reference not set to an instance of an object UnityEditor.Graphs.Edge.WakeUp () (at C:/buildslave/unity/build/Editor/Graphs/UnityEditor.Graphs/ Edge.cs:114) 。
What should I do?我该怎么办? I'm doing this game for a game jam so I need to resolve this problem quickly.我正在做这个游戏是为了游戏果酱,所以我需要快速解决这个问题。 Thank you.谢谢你。
EDIT : I noticed that I can flip the sprite in the editor, but that I can't do that using scripts.编辑:我注意到我可以在编辑器中翻转精灵,但我不能使用脚本来做到这一点。
From this thread I found , it seems like an old bug from Unity's UnityEditor.Graphs.DLL code.从我发现的这个线程中,它似乎是 Unity 的 UnityEditor.Graphs.DLL 代码中的一个旧错误。
Try restarting Unity completely.尝试完全重新启动 Unity。
This bug seems to occur only in the editor, and not after a game is built, so you should be safe.这个错误似乎只发生在编辑器中,而不是在构建游戏之后发生,所以你应该是安全的。
I haven't worked on any 2D Unity projects in a while but here is a piece of code I used to resolve that issue in the past.我有一段时间没有参与任何 2D Unity 项目,但这是我过去用来解决该问题的一段代码。 Let me know if it helps.如果有帮助,请告诉我。
private void FlipSprite()
{
bool playerHasHorizontalSpeed = Mathf.Abs(myRigidBody.velocity.x) > Mathf.Epsilon;
if(playerHasHorizontalSpeed)
{
transform.localScale = new Vector2(Mathf.Sign(myRigidBody.velocity.x), 1f);
}
}
This is a bit old so be sure to let me know how this works.这有点旧,所以一定要让我知道它是如何工作的。 You'll need to finish the rest of the controls, but this should work.您需要完成其余的控件,但这应该可以工作。
public class SpriteFlipper : MonoBehaviour
{
// variable to hold a reference to our SpriteRenderer component
private SpriteRenderer mySpriteRenderer;
// This function is called just one time by Unity the moment the component loads
private void Awake()
{
// get a reference to the SpriteRenderer component on this gameObject
mySpriteRenderer = GetComponent<SpriteRenderer>();
}
// This function is called by Unity every frame the component is enabled
private void Update()
{
// if the A key was pressed this frame
if(Input.GetKeyDown(KeyCode.A))
{
// if the variable isn't empty (we have a reference to our SpriteRenderer
if(mySpriteRenderer != null)
{
// flip the sprite
mySpriteRenderer.flipX = true;
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.