Rookie
Rookie

Reputation: 193

Unity: Can't get reference to a class via getcomponent

    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));
        }
      }

I get the error:

NullReferenceException: Object reference not set to an instance of an object CartMovement.Start () (at Assets/scripts/CartMovement.cs:25)

I don't understand why I can't get a reference to another script. Can anyone fix this. thanks.

Upvotes: 0

Views: 1745

Answers (1)

Vect0rZ
Vect0rZ

Reputation: 401

If the level manager is attached to another object (as you mentioned in the comments), one way is to reference that object through the inspector and then get the script from that object.

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
    }
}

Upvotes: 1

Related Questions