Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Voting for the Unity Awards are OPEN! We’re looking to celebrate creators across games, industry, film, and many more categories. Cast your vote now for all categories
    Dismiss Notice
  3. Dismiss Notice

Setting Reference in Start() doesn't work

Discussion in 'Scripting' started by leoggwp, Feb 22, 2018.

  1. leoggwp

    leoggwp

    Joined:
    Feb 22, 2018
    Posts:
    10
    I want to to set the reference in the Start-function to use it later in the script..like this:

    public class FallObjectScript : MonoBehaviour {

    public GameObject gameController;

    void Start()
    {
    Debug.Log ("Test");
    GameObject gameController = GameObject.FindWithTag("GameController");
    }

    void OnMouseDown()
    {
    gameController.GetComponent<GameControllerScript>().AddPoints(5);
    Destroy (gameObject);
    }
    }


    But it just works like this:

    public class FallObjectScript : MonoBehaviour {

    public GameObject gameController;

    void OnMouseDown()
    {
    GameObject gameController = GameObject.FindWithTag("GameController");
    gameController.GetComponent<GameControllerScript>().AddPoints(5);
    Destroy (gameObject);
    }
    }


    If i set the reference in the Start-function it says: "...Object reference not set to an instance of an object...".
    Why dosen't it work?
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,140
    change
    GameObject gameController = GameObject.FindWithTag("GameController");

    to

    gameController = GameObject.FindWithTag("GameController");
     
  3. leoggwp

    leoggwp

    Joined:
    Feb 22, 2018
    Posts:
    10
    Thank you verry much. Was really simple now, but I am quite new in Unity so didn't notice what went wrong. :)
     
  4. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,140
    Well, this is not really related to Unity directly. Basically, if you declare a global variable, but then declare it again inside a method, when you try to assign something to the variable, it only uses it in that method instead of saving the reference to the global variable.