MissingComponentException:“Koopa Troopa”游戏对象没有附加“SpriteRenderer”,但是脚本正在尝试访问它

时间:2017-12-18 17:43:03

标签: unity3d sprite

错误如下:

MissingComponentException:“Gumbaa”游戏对象没有附加“SpriteRenderer”,但是脚本正在尝试访问它。您可能需要向游戏对象“Gumbaa”添加SpriteRenderer。或者您的脚本需要在使用之前检查组件是否已连接。 UnityEngine.Renderer.get_bounds()(在/Users/builduser/buildslave/unity/build/artifacts/generated/common/runtime/GraphicsBindings.gen.cs:1007)EnemyMovement.Start()(在Assets / Scripts / EnemyMovement.cs上) :21)

每当我点击播放按钮时,我的游戏也会自动暂停。

当我尝试将组件'SpriteRenderer'添加到Gumbaa时,我接收到另一条错误消息,如下所示:无法向Koopa Troopa添加组件'SpriteRenderer',因为它与现有的'MeshFilter'派生组件冲突!

Screenshot of inspector

using System.Collections;
using UnityEngine;

public class EnemyMovement : MonoBehaviour 
{
public float speed = 2.7f;
public LayerMask EnemyMask;

Transform myTrans;
float myWidth, myHeight;
Rigidbody2D rb;
SpriteRenderer mySprite;

// Use this for initialization
void Start () 
{
    myTrans = this.transform;
    rb = this.gameObject.GetComponent<Rigidbody2D> ();

    mySprite = this.gameObject.GetComponent<SpriteRenderer> ();
    myWidth = mySprite.bounds.extents.x;
    myHeight = mySprite.bounds.extents.y;
}

// Update is called once per frame
void FixedUpdate () 
{
    Physics2D.IgnoreLayerCollision (8, 9);
    Vector2 LineCastPos = (myTrans.position.toVector2() +         myTrans.right.toVector2() * myWidth + Vector2.up * myHeight * 1.2f);

    Debug.DrawLine (LineCastPos, LineCastPos +          myTrans.right.toVector2 () * 1.2f);

    bool isBlocked = Physics2D.Linecast (LineCastPos, LineCastPos +     myTrans.right.toVector2 () * 1.2f, EnemyMask);


    if (isBlocked) 
    {
        Vector2 currRot = myTrans.eulerAngles;
        currRot.y += 180;
        myTrans.eulerAngles = currRot;
    }

    Vector2 myVel = rb.velocity;
    myVel.x = myTrans.right.x * speed ;
    rb.velocity = myVel;
}
}

1 个答案:

答案 0 :(得分:0)

错误很明显:

在您的Gumba对象上,您添加了脚本EnemyMovement

在脚本中,你做

mySprite = this.gameObject.GetComponent<SpriteRenderer> ();

这意味着拥有EnemyMovement的GameObject也必须具有SpriteRenderer

在UnityInspector中,执行AddComponent并选择SpriteRenderer

知道你是否真的需要使用精灵渲染器取决于你