• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by Nephtis · Aug 29, 2016 at 10:56 AM · scene-loadingfindobjectoftype

FIndObjectOfType Problem when Changing Scenes

When I change scenes using:

 SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);

I keep the player and some other objects constant (because I want them to be transferred between scenes). In my scripts, I've got FindObjectOfType() etc. in the Start() function, however this doesn't seem to be fast enough sometimes, as I end up with references to old gameObjects (e.g. that are replaced by the new gameObjects coming from the other scene). I might have a dummy player in the scene so I can test it, but in the actual game, that player will get replaced by the "real" player when they change scenes.

My current workaround is to have a bool flag, then in the Update() loop after a timer of 0.01s, I do the FindObjectOfType stuff there, then turn the flag on. This means the references are all correct, but doesn't seem like a good way of handling this problem.

Some pseudocode:

 private Player myPlayer;
 private bool foundPlayer;
 private float waitTime;

 Start(){
     myPlayer = FindObjectOfType<Player>(); // Sometimes not fast enough...
     waitTime = 0.01f;
 }

 Update(){
     if (waitTime > 0){
         waitTime -= Time.deltaTime; // Count down for 0.01s
     }
     if (!foundPlayer && waitTime <= 0){ // After 0.01s, if we don't have the reference
         myPlayer = FindObjectOfType<Player>(); // Set the correct reference
         foundPlayer = true;
     }
 }

Is there a better solution to this?

Comment
Add comment · Show 3
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image TanselAltinel · Aug 29, 2016 at 12:42 PM 1
Share

Why not use a CoRoutine that will start 0.1 seconds after the Start call?

Show more comments

1 Reply

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by Cynikal · Aug 29, 2016 at 03:41 PM

If you want to do a call when a new scene was loaded, why not use:

 void OnLevelWasLoaded()
 {
 //Blah Blah this only works when using SceneManager.Load
 }
 
 //OR
 
 void OnLevelWasLoaded(int sceneindex)
 {
 //Blah Blah this only works when using SceneManager.Load
 }

As far as the old gameobjects, i'm assuming you're using a list. You could remove the "bad" gameobjects with something along the lines of:

 MyHashSet.RemoveWhere(s => s == null);

This is helpful if a gameObject was once there...but has been unloaded (aka, switched scenes), therefore, it'd be null.

Comment
Add comment · Show 3 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Nephtis · Aug 29, 2016 at 03:50 PM 0
Share

Thanks for telling me about this function, I'm doing something similar with the removal of old gameObjects, unfortunately doing it this way still leads me to the problem of:

  • Load into a new scene (from another scene)

  • The "OnLevelWasLoaded()" function immediately gets called and starts pointing to the old gameObject (the one that gets replaced)

  • The gameObjects are then switched (I can't seem to change the order this happens in, the switching always seems to come last), but everything is still pointing to the old gameObjects

So what I need to do is do the switching BEFORE I set the references to things - this is why I had that 0.01s delay, just to make sure everything was loaded and switched before pointing things at it.

The way I remove old gameObjects is:

 private static bool playerExists;

 // ...

         if (!playerExists) // If a player doesn't exist in the scene
         {
             playerExists = true; // Now a player does exist
             DontDestroyOnLoad(transform.gameObject);
         }
         else // if a player does already exist in the scene
         {
             Destroy(gameObject); // Destroy it
         }
avatar image Cynikal ♦ Nephtis · Aug 29, 2016 at 03:56 PM 1
Share

The RemoveWhere portion was intended to remove any null gameobjects.

Regarding the OnLevelWasLoaded, you could initiate a Coroutine that has a built in .1sec delay, ultimately getting you far away from doing it in the Update.

If you have objects A, B, and C on Scene 1. Then you load into Scene 2, and now you have objects D, E, and F. Objects A, B, and C are now null.

avatar image Nephtis Cynikal ♦ · Aug 29, 2016 at 04:07 PM 0
Share

Ok, so I ended up doing that with a 0.01s delayed coroutine, and it does save me having to do it from within Update() every time. Having to manually delay it still kind of sucks but until I can figure out how to change the order of things happening on scene load, this works well for now.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

53 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Display loading/progress indicator from Start()? 0 Answers

put a void in an if statement? 1 Answer

LoadScene problem 1 Answer

Using parameters of activeSceneChanged? 0 Answers

Unity crashes after oping a scene from unity collaborate? 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges