Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

C# PlayerPrefs can only be called within a MonoBehavior script?

Discussion in 'Scripting' started by vinfang, Oct 31, 2013.

  1. vinfang

    vinfang

    Joined:
    Jul 13, 2013
    Posts:
    14
    So we ran into a bug that took us 4 hours to figure out, but is it true that when calling PlayerPrefs it must be done in a MonoBehavior script attached to an active game object?

    We got an error in the Unity Console that I ignored for some reason that Unity didn't like you calling GetString (I'm assuming it could have been any of PlayerPrefs methods) outside of the Unity Main thread.

    Is this correct or am I calling the PlayerPrefs functions wrong? They're all static class functions so I'm not sure how else to be using this.
     
  2. rutter

    rutter

    Joined:
    Mar 21, 2012
    Posts:
    84
    Parts of Unity are multi-threaded; certain resources are only allowed to be accessed from certain threads. For the most part, behaviour scripts we write will be run from the main thread.

    When I get errors like that, it's usually because I'm trying to run something in a static constructor that's being called during level load. I can usually get around it by deferring those calls until Awake() or Start() are called.