0
\$\begingroup\$

I'm trying to have an object with the DontDestroyOnLoad property. I want an object with NetworkIdentity to persist across scenes, so I can have a holder script for RPCs.

This answer suggests the following code:

public void Awake()
{
    DontDestroyOnLoad(this);

    if (FindObjectsOfType(GetType()).Length > 1)
    {
        Destroy(gameObject);
    }
}

Despite this, I still end up with duplicate objects. FindObjectsOfType(GetType()).Length is always returning 1, and I don't know why, or how to fix it. It makes no difference whether this object is a prefab instance or a simple object in the hierarchy.

I have also tried to clone this object in my NetworkManager script, which is automatically persistent, but GameObject.Find("ObjectNameHere(Clone)") is always returning false. However, the above solution seems simpler so I'd prefer to figure out FindObjectsOfType(GetType()).Length.

\$\endgroup\$
2
\$\begingroup\$

You better use Singleton pattern which ensures that object will exist in in a single copy:

public class ExampleClass: MonoBehaviour {
    public static ExampleClass instance = null;

    void Start () {
        if (instance == null) {
            instance = this;
        } else if(instance != this){
            Destroy(gameObject);
        }

        DontDestroyOnLoad(gameObject);

        InitializeManager();
    }

    private void InitializeManager(){
        // TODO: add initialization code here
    }
}

And you don`t even need to use heavy FindObjectsOfType() method.

\$\endgroup\$
1
\$\begingroup\$

Try this. It compares time alive on different instances of the class, ensuring that your first instance will be the one that survives.

public class ExampleClass : MonoBehaviour {

    float time = 0;

    void Awake () {
        DontDestroyOnLoad(this);
    }

    void Update () {
        time += Time.deltaTime;
    }

    private void OnLevelWasLoaded(int level)
    {
        foreach (ExampleClass classInstance in FindObjectsOfType<ExampleClass>())
        {
            if (classInstance.time < time)
            {
                Destroy(classInstance);
            }
        }
    }
}

Hope this helps. It's not the way you would like, but it is functional.

\$\endgroup\$
  • \$\begingroup\$ Why would you bother checking each frame for time if you can atleast toggle a simple bool upon first object initialization? \$\endgroup\$ – RiotBr3aker Aug 16 '18 at 1:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.