Component goes away on play?

127095-question2.jpg
I’m trying to attach the game object Player to a script, and it works, but once I enter play mode, it detaches from the script? Is it just some simple thing I’m missing? =/

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor.SceneManagement;

public class Portal : MonoBehaviour {

private bool backToMoon = false;
int levelToLoad = 1;
[SerializeField] GameObject Player;

// Use this for initialization
void Start () {
    DontDestroyOnLoad(this);
    Player = GetComponent<GameObject>();
    print("Won't be destroyed!");
    if (FindObjectsOfType(GetType()).Length > 1)
    {
        Destroy(gameObject);
    }
}
// Update is called once per frame
void Update () {

}
private void LoadScene()
{
    int doomPortal = Random.Range(0, 100);
    print(doomPortal);
    if (doomPortal == 66)
    {
        EditorSceneManager.LoadScene(2);
        print("Doom World...");
        levelToLoad = 0;
        return;
    }
    if (levelToLoad == 1)
        {
        Player.transform.Translate(0, 0, 0);
        print("Move Character to 0,0,0");
        levelToLoad = 0;
        return;
    }
    if (levelToLoad == 0)
    {
        EditorSceneManager.LoadScene(levelToLoad);
        levelToLoad = 1;
        return;
    }
}
/*private void OnCollisionEnter2D(Collision2D collision)
{
    LoadScene();
    print ("Scene Loaded");
}
*/

private void OnTriggerEnter2D(Collider2D collision)
{
    if (collision.CompareTag("Player"))
    {
        LoadScene();
        print("Scene Loaded");
    }
}

}

You’re obviously trying to make a Singleton. Although Start() is called on every object in sequence, Destroy doesn’t destroy the object immediately, so the following will return true on most objects.

if (FindObjectsOfType(GetType()).Length > 1)

You rather want to assign a static unique instance member, and self destroy if it’s already assigned.

public static Portal instance;
void Awake ()
{
    DontDestroyOnLoad(gameObject);
    if (instance == null)
        instance = this;
    else
        Destroy(gameObject);
}

Side notes :

  • GetComponent() makes no sense, use the gameObject property instead
  • Pass the gameObject to DontDestroyOnLoad instead of the component
  • Prefer doing this in Awake than Start
  • Your Player field is a SerializeField, why assigning it upon Start ?
  • I don’t think you need a reference to the Player, as you use a tag to filter the trigger.