Trying to understand the docs manual. (Accessing game objects through scripts in C#)

So, re-entering the world of Unity and C#, I spent hours trying to figure out how to access a function inside another script. While I already found a solution, what bothered me was the following in docs.unity3d.com :

using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
    void Update() {
        OtherScript otherScript = GetComponent<OtherScript>();
        otherScript.DoSomething();
    }
}

And here is my code:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System;
using System.Text;
using System.Linq;
using Random = UnityEngine.Random;

public class TestScript : MonoBehaviour {
    void Start() {
        TextChanger2 textChanger2 = GetComponent<TextChanger2>();
        textChanger2.PrintTest2();
    }
}

Here is the code from TextChanger2 script:

using UnityEngine;
using System.Collections;

public class TextChanger2 : MonoBehaviour {

    // Use this for initialization
    void Start() {
    }

    public void PrintTest2() {

        print("I am in printTest2 inside TextChanger2");

    }
}

Using this code this way produces the following error in the Unity console:

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

What am I missing? To make it work, I had to locate the game object first and then the script afterwards. I guess I just want to know, was I following the instructions incorrectly by looking at it verbatim? Or was it assumed that I had already located the game object at the time that instruction was written?

If your two scripts are on different objects, you will need to find the find a reference to the object that has the other script has a component, like so :

In TestScript :

 public class TestScript : MonoBehaviour {
     void Start() {
         GameObject textObject = GameObject.Find("SecondObjectNameHere");
         TextChanger2 textChanger2 = textObject.GetComponent<TextChanger2>();
         textChanger2.PrintTest2();
     }
 }

Be sure to replace “SecondObjectNameHere” by the name of your gameobject in your scene.

Also, you’d want to avoid using the GameObject.Find() Method since it is not well optimized. You could use FindWithTag or set the GameObject public and set it in the inspector.

It seems your game object doesn’t have the “TextChanger2” component attached. Be sure that both “TestScript” and “TextChanger2” are attached to the same game object.