Search Unity

NullReferenceException calling another script

Discussion in 'Scripting' started by JackieFrost, Aug 14, 2019.

  1. JackieFrost

    JackieFrost

    Joined:
    Feb 6, 2016
    Posts:
    2
    Hello there!
    I'm having some problems calling another script, what's weird is two days ago it worked, but anyway I get NullReferenceException : Object reference not set to an instance of an object.
    This is the code:

    public class Googlemaps : MonoBehaviour

    {
    private TouchTower script;

    // Start is called before the first frame update
    void Awake()
    {
    script = GetComponent<TouchTower>();
    }

    // Update is called once per frame
    public void googlemaps(string google)
    {

    if (script.iminhoven == true)
    {
    Application.OpenURL("http://maps.apple.com/maps?saddr=Current+Location&daddr=39.717053,3.475234");
    }

    im trying to open the navigator with that coordinates when your press a button.
    In the other script I have booleans which say what place has to look for (IminX)

    As I understand I think is not finding the other script for some reason, but this error only appears in game when I press the button and in the script I do not have any errors. Any idea? Thanks a lot
     
  2. ismaelflorit

    ismaelflorit

    Joined:
    Apr 16, 2019
    Posts:
    38
    Hi !

    Please use code tags when posting code.

    Which line of your script is throwing the error?

    Not having errors in your script is great, as otherwise the code won't compile. However keep in mind that runtime errors (like a NullReferenceException) are not checked during compilation.

    Is the TouchTower script attached?
    Has it been modified recently causing the script to not be identified in Unity?
     
  3. JackieFrost

    JackieFrost

    Joined:
    Feb 6, 2016
    Posts:
    2
    I fixed it, just changed:
    script = GetComponent<TouchTower>();
    For:
    script = FindObjectOfType<TouchTower>();
     
    ismaelflorit likes this.
  4. ismaelflorit

    ismaelflorit

    Joined:
    Apr 16, 2019
    Posts:
    38
    Glad that's sorted it! Keep in mind that FindObjectOfType is very slow as Unity points out in their doc. If TouchTower isn't static, I would simply make the TouchTower script public and drag and drop the reference to it.