Unity 2D精灵不会翻转

时间:2020-02-07 20:16:07

标签: c# unity3d

我正在使用Unity 2D进行平台游戏,我想在玩家向左移动角色精灵时将其向左翻转,但是由于某些原因,它不起作用。我试图制作一个脚本:

transform.rotation = new Vector3(0f, 180f, 0f);

但是没有用。所以我写了这个:

transform.localScale = new Vector3(-0.35f, 0.35f, 1f); //the player's scale x and y are 0.35 by default

但是它也不起作用。然后,我在控制台中发现以下错误消息: NullReferenceException:对象引用未设置为对象的实例 UnityEditor.Graphs.Edge.WakeUp()(在C:/buildslave/unity/build/Editor/Graphs/UnityEditor.Graphs/Edge.cs:114)

我该怎么办?我正在做这个游戏时遇到游戏卡纸,所以我需要快速解决此问题。谢谢。

编辑:我注意到可以在编辑器中翻转精灵,但是我无法使用脚本来做到这一点。

3 个答案:

答案 0 :(得分:2)

this thread I found中,这似乎是Unity的UnityEditor.Graphs.DLL代码中的旧错误。

尝试完全重启Unity。

此错误似乎仅在编辑器中发生,而不是在构建游戏之后发生,因此您应该很安全。

答案 1 :(得分:0)

我已经有一段时间没有在任何2D Unity项目中工作了,但这是我过去用来解决该问题的一段代码。让我知道是否有帮助。

    private void FlipSprite()
        {
            bool playerHasHorizontalSpeed = Mathf.Abs(myRigidBody.velocity.x) > Mathf.Epsilon;
            if(playerHasHorizontalSpeed)
            {
                        transform.localScale = new Vector2(Mathf.Sign(myRigidBody.velocity.x), 1f);

            }
        }

答案 2 :(得分:0)

这有点老了,所以一定要让我知道它是如何工作的。您需要完成其余的控件,但这应该可以工作。

      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;
            }
        }
    }
}
相关问题