Help With Public Variable Access Using Get Component

Hi Everyone.
I hope you are all ok.
Newbie to Unity here, going mad looking at sharing variables between scripts.
I have done loads of googling and reading and I must be making a very basic mistake somewhere.

I simply want, as a learning exercise, to create a string as public in one script and print it to the console in another script.

I have spent ages online - into my third day, so please put me out of my misery.

To keep it really simply I took the example from the unity.learn area:

and made my own mini version.

And no matter how much I tidy it up and look for mistakes I always get the error

NullReferenceException: Object reference not set to an instance of an object
ScriptNo2.Start () (at Assets/Scripts/ScriptNo2.cs:15)

If anyone can help me I will be eternally grateful.

Andy

===

So here are the two scripts:

First the one to create the string:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScriptNo1 : MonoBehaviour
{
    public string outText = "Bernie Sanders";
}

and second the one to access that variable and print it to console:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ScriptNo2 : MonoBehaviour
{
    private ScriptNo1 scriptNo1;

    void Awake()
    {
        scriptNo1 = GetComponent<ScriptNo1>();
    }
    void Start()
    {
        Debug.Log("A message from Start in Script 2 drawing variable from Script 1 " + scriptNo1.outText);
    }
}

Make sure you put both scripts on the same game object. The GetComponent<>() method is running on the current game object, which means it only finds components on it.
Here I put them on my Main Camera for test:
7085758--843478--screenshot1.png

1 Like

Wow. You are very quick to reply. But I guess that is what a lurking Ninja does!

Thank you so much for your help. It works perfectly now and I can move on !

And as I said, I am eternally grateful!

Andy

2 Likes