Unity:无法通过getcomponent获取对类的引用

时间:2017-02-12 15:36:52

标签: c# unity3d

    using UnityEngine;

    public class CartMovement : MonoBehaviour {

    SpriteRenderer spriteRenderer;

    LevelManager LevelManIns;

    void Start () {

        spriteRenderer = GetComponent<SpriteRenderer>();

        spriteRenderer.enabled = true;

        (line25)LevelManIns = GetComponent<LevelManager>();

        Debug.Log("--" + LevelManIns.xy.X);
        //transform.position = LevelManIns.Tiles[LevelManIns.PortalGreen].GetComponent<TileScript>().transform.position;

        iTween.MoveTo(this.gameObject, iTween.Hash("path", iTweenPath.GetPath("cartPath"), "time", 3));
        }
      }

我收到错误:

NullReferenceException:未将对象引用设置为对象的实例 CartMovement.Start()(在Assets / scripts / CartMovement.cs:25)

我不明白为什么我无法获得对另一个脚本的引用。谁能解决这个问题。感谢。

1 个答案:

答案 0 :(得分:1)

如果级别管理器附加到另一个对象(如您在注释中所述),则一种方法是通过检查器引用该对象,然后从该对象获取脚本。

public class CartMovement : MonoBehaviour {

SpriteRenderer spriteRenderer;
// Make it public, so it is visible in the inspector, and drag and drop the object into that instance
public LevelManager LevelManIns; 

    void Start () {
        // No need to assign it here, just maybe check if it is assigned like so
        if (LevelManIns == null)
            // Error, this should be assign outside
    }
}