Jump to content
  • Advertisement
Sign in to follow this  
FGFS

Unity CreateInstance can only be called from the main thread.

This topic is 1366 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi
New to Unity and c# I get:

CreateInstance can only be called from the main thread.
Constructors and field initializers will be executed from the loading thread when loading a scene.
Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function.

How to rewrite and/or put into the main cs?
private BSplineMath bmath = ScriptableObject.CreateInstance("BSplineMath") as BSplineMath;

 

If I put that in the main class I get a reference error:

error CS0103: The name `bmath' does not exist in the current context
 

No wonder, how to use an instance in another class. In c++ I would only

include the header?
Many thanks in advance

 

Edited by FGFS

Share this post


Link to post
Share on other sites
Advertisement
Not familiar with Unity, but I do know C#. Based on the text in the error message you posted you want:
 
private BSplineMath bmath;
in your class, and then in some kind of Awake or Start function (defined by Unity most likely?) put your initialization code:
 
bmath = ScriptableObject.CreateInstance("BSplineMath") as BSplineMath;
Basically, you're splitting up the definition of the variable and the initialization since (apparently) Unity doesn't like you calling CreateInstance when an instance of your class is constructed.

Share this post


Link to post
Share on other sites

You need to post some code. Show the code where you are initialising bmath and the code where you want to use it.

 

From the error message you've posted I suspect you have something like this:

// Spline.cs

public class Spline
{
    private BSplineMath bmath = ScriptableObject.CreateInstance("BSplineMath") as BSplineMath;
}

// program.cs
public class Program
{
    static void Main(string[] args)
    {
        bmath.Something();
    }
}

If you want to use bmath in your Main (probably a bad idea, btw) you need to get a reference to it somehow.

Share this post


Link to post
Share on other sites
So, the "main thread" is a completely different thing than "main cs". Explaining what a thread is...unfortunately a pretty complex topic and is beyond the scope of this discussion.

The correct solution in this case looks like this (like what SmkViper said):
 
public class YourClass : MonoBehaviour
{
    private BSplineMath bmath;

    void Awake() // NOTE: Unity always calls Awake on its main thread.
    {
        bmath = ScriptableObject.CreateInstance("BSplineMath") as BSplineMath;
    }
}
Edited by Nypyren

Share this post


Link to post
Share on other sites

Thanks, I didn't know about awake nor didn't have that at all. Now it compiles but at runtime I get:

NullReferenceException: Object reference not set to an instance of an object
BSplineSurface.Init () (at Assets/BSplineSurface.cs:64)
 

The last line below is 64. Many thanks again in advance.

 

 

public class BSplineSurface : ScriptableObject {
   
    /*
     * THESE VALUES MUST BE SET BEFORE CALCULATING
     */
    //size of the control net (e.g. 3x4 net)
    public int NI = 4; //setting these to high can crash unity
    public int NJ = 4;
    //Grid of control points
    public Vector3[,] controlGrid;

    //The degree in each direction
    public int TI = 3;
    public int TJ = 3;
    //output GRID resolution (e.g. 30x40)
    public int RESOLUTIONI = 150; //setting these to high can crash unity
    public int RESOLUTIONJ = 150;
    //the output Grid
    public Vector3[,] outputGrid;
    public BSplineMath bmath;
    /*
     * INTERNAL VALUES
     */
    //internal knots in each direction
    private int[] knotsI;
    private int[] knotsJ;
    //internal variables
    private int i, j, ki, kj;
    private float intervalI, incrementI, intervalJ, incrementJ, bi, bj;
   
    //FUNCTIONS

    void Awake() // NOTE: Unity always calls Awake on its main thread.
    {
        bmath = ScriptableObject.CreateInstance("BSplineMath") as BSplineMath;
    }
 

    //constructor

    public BSplineSurface()
    {
        Init();
    }
 
    //MUST BE CALLED FIRST
    public void Init () {

        controlGrid = new Vector3[NI+1,NJ+1];
        outputGrid = new Vector3[RESOLUTIONI, RESOLUTIONJ];
       
        //init step size (the increment steps)
        incrementI = (NI-TI+2) / ((float)RESOLUTIONI - 1);
        incrementJ = (NJ-TJ+2) / ((float)RESOLUTIONJ - 1);
       
        //Calculate KNOTS
        knotsI = bmath.SplineKnots(NI, TI);

Share this post


Link to post
Share on other sites

You Init() method runs on constructions, and makes use of the "bmath" field. Since that field isn't populated until Awake() is called (which is necessarily after construction), you are getting a NullReferenceException.

 

Given the constraints that BSplineMath has about which thread it is called from, you'll probably need to defer calculating the spline knots until Awake() is called. At this point, your constructor / Init() method aren't really giving you a lot of value - it might make sense to put all your initialisation code in the Awake() method.

 

I'd also mention that some of your fields, in particular "i, j, ki, kj" look like they should probably be local variables.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
  • Advertisement
  • Popular Tags

  • Popular Now

  • Advertisement
  • Similar Content

    • By Aryndon
      Project Redemption is an semi-fantasy RPG with a linear story and an elaborate combat system.
      We are building in Unity and are currently looking animators and artists.
      What we are looking for
      -Someone who is okay with split revenue/profits when finished
      -Collaborate with others in the team. Do you have an idea/thought on what should be included? Tell us!
      -Someone who wants to work with people that are passionate about this project
      If you are interested. Please message me and I will get back to you as soon as possible! Or add me on Discord AJ#6664
    • By Aggrojag
      Hello!
      I'm working on a game that is a narrative driven dark comedy with some small aspects of platforming and puzzle solving. The project is rather small as well. It touches on topics such as suicide, mental illness, family, corruption, free-will, and redemption.
      This project is exercise in polish, this means some experimentation will be needed along with some reworking of assets as they're provided.
      This will be a revshare model.
      First, I'm looking for a 2D sprite artist, not pixelated, that can compliment the style of the attached images, and be similar to the temporary character.
      We are looking to bring on a SFX designer at this time. Full list of required SFX will be available upon request, as well as a build with all elements related to sound implemented in some form (many SFXs pulled from the web for now). Will likely require some field recording, and some pretty strange SFX for when things get weird. I imagine a good portion of these will be quite fun to create.
      Lastly, I'm looking for a male voice actor, English should be your primary language. There will be at minimum two characters that will need to be brought to life through vocals. The first voice is similar to Marvin from Hitchhiker's Guide to the Galaxy. A reference for the second voice would be a mix of Ren (Ren & Stimpy), and Android 21 (DragonBallFighterZ). Due to formatting, I'm not including YouTube links in the post, sorry.
       
      WIP Scene with our custom shaders attached (platforms are lazily placed, as this was an asset test):

      A scene with dynamic lighting and temp character:

       
      Unshaded asset:

      If you made it to the bottom, thank you, and I look forward to hearing from you.
    • By SickTwistGames
      Ok, firstly, Hi.
       
      This is my first post on this forum. I am an Indie Dev making my first game so bear with me when I say dumb stuff, I'm on a huge learning curve.
       
      My first question is about inventory systems for unity. I am trying to make a survival type game with crafting. I have purchased Inventory manager pro by devdog from the unity asset store and it seems like a pretty powerful assett but for an intermediate coder its a little tough to use.  I'm beginning to wonder if it was the right purchase.
      So my question is.... does anyone have any experience of inventory plugins / systems for unity and can anyone reccomend a system to me?
      It needs to have the following: Loot system, crafting system, character sheet, blueprint system,  character stats system. Ideally with as little coding as possible.
       
      Thanks
    • By ethancodes
      I've got a bug with my brick breaker style game. The bricks move down one line at a time ever 1.5 seconds. What appears to be happening is occasionally the ball will be just about to hit the brick when the brick moves down a line, and now the ball is behind it. I'm not sure how to fix this. I have two ideas but I'm not sure of implementation. 1 solution would be to check where they were and where they are going to be before rendering the frame. Then if they crossed paths, then register the brick as hit. Solution 2 would be change how the bricks move. I could maybe slide them down line by line, instead of a jump down. I'm not sure of this will fix the issue or not. Any ideas?
    • By Pixeye
      I wrote an extension for unity inspector that allows to group/fold variables. 
      Available on github  , cheers!

       
  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!