save a public GameObect and instantiate it on new scene - C#

I’m creating a game where some NPCs can follow the player, however I want them to also follow the player onto new scenes. What I’ve tried to do is store the companion into a static GameObject variable, and then instantiate it on the new scene. The problem is, it loses the reference and won’t work.

(Quick example of what Im trying to do)
public static GameObject companion;

if (doesSomething) {
companion.GameObject = other.GameObject;
}

//and on a new level
void Start () {
companion = instantiate(companion, transform.position, Quaternion.identity) as GameObject;
}

The console tells me its getting a null reference, or something like it no longer exists. This makes me think its only storing the reference. Is there some way to store it as a new object? like a new prefab or something?

Any help would be much appreciated.

Making the NPC’s objects that do not get destroyedonload will mean that when you load a new scene, these objects persist to the new scene.
Put this line of code in your Start() or Awake() function on a script attached to the object to prevent it from being destroyed.
I recommend you place it in your Awake() Function.

DontDestroyOnLoad(gameObject);

Have Fun!

You set companion to an instance of an object in the scene.
Then you change scenes.
This destroys the object.
You now have a reference to null

What you can do, is keep a structure that holds the informations to spawn the companion.

For example

 struct CompanionData
    {
        string name;
        int hp;
        bool lovesBananas;
    }
    
    public class Companion : MonoBehaviour
    {
        CompanionData data;
    ...
    }

Persist your data in a static variable if you’d like (it’s not a monobehaviour, it will not be destroyed when unloading the scene) and when you instantiate your companion, set it up with the data.