• Advertisement
Sign in to follow this  

Unity CreateInstance can only be called from the main thread.

This topic is 1242 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

  • Advertisement
  • Popular Now

  • Similar Content

    • By NDraskovic
      Hey guys,
      I have a really weird problem. I'm trying to get some data from a REST service. I'm using the following code:
       
      private void GetTheScores() { UnityWebRequest GetCommand = UnityWebRequest.Get(url); UnityWebRequestAsyncOperation operation = GetCommand.SendWebRequest(); if (!operation.webRequest.isNetworkError) { ResultsContainer rez = JsonUtility.FromJson<ResultsContainer>(operation.webRequest.downloadHandler.text); Debug.Log("Text: " + operation.webRequest.downloadHandler.text); } } The problem is that when I'm in Unity's editor, the request doesn't return anything (operation.webRequest.downloadHandler.text is empty, the Debug.Log command just prints "Text: "), but when I enter the debug mode and insert a breakpoint on that line, then it returns the text properly. Does anyone have an idea why is this happening?
      The real problem I'm trying to solve is that when I receive the text, I can't get the data from the JSON. The markup is really simple:
      [{"id":1,"name":"Player1"},{"id":2,"name":"Player2"}] and I have an object that should accept that data:
      [System.Serializable] public class ResultScript { public int id; public string name; } There is also a class that should accept the array of these objects (which the JSON is returning):
      [System.Serializable] public class ResultsContainer { public ResultScript[] results; } But when I run the code (in the debug mode, to get any result) I get an error: ArgumentException: JSON must represent an object type. I've googled it but none of the proposed solutions work for me.
      Also (regardless if I'm in the debug mode or not) when I try to do some string operations like removing or adding characters to the GET result, the functions return an empty string as a result
      Can you help me with any of these problems?
      Thank you
    • By nihitori
      The Emotional Music Vol. I pack focuses on beautiful and esoteric orchestral music, capable of creating truly emotive and intimate moods. It features detailed chamber strings, cello and piano as the main instruments, resulting in a subtle and elegant sound never before heard in video game royalty-free music assets.

      The pack includes 5 original tracks, as well as a total of 47 loops based on these tracks (long loops for simple use and short loops for custom / complex music layering).

      Unity Asset Store link: https://www.assetstore.unity3d.com/en/#!/content/107032
      Unreal Engine Marketplace link: https://www.unrealengine.com/marketplace/emotional-music-vol-i

      A 15 seconds preview of each main track is available on Soundcloud:
       
    • By RoKabium Games
      Another one of our new UI for #screenshotsaturday. This is the inventory screen for showing what animal fossils you have collected so far. #gamedev #indiedev #sama
    • By eldwin11929
      We're looking for programmers for our project.
      Our project is being made in Unity
      Requirements:
      -Skills in Unity
      -C#
      -Javascript
      -Node.js
      We're looking for programmers who can perform a variety of functions on our project.
      Project is a top-down hack-and-slash pvp dungeon-crawler like game. Game is entirely multiplayer based, using randomized dungeons, and a unique combat system with emphasis on gameplay.
      We have a GDD to work off of, and a Lead Programmer you would work under.
      Assignments may include:
      -Creating new scripts of varying degrees specific to the project (mostly server-side, but sometimes client-side)
      -Assembling already created monsters/characters with existing or non-existing code.
      -Creating VFX
      -Assembling already created environment models
      If interested, please contact: eldwin11929@yahoo.com
      This project is unpaid, but with royalties.
       
      ---
      Additional Project Info:
      Summary:
      Bassetune Reapers is a Player-verus-Player, competitive dungeon crawler. This basically takes on aspects of dungeon crawling, but with a more aggressive setting. Players will have the option to play as the "dungeon-crawlers" (called the 'Knights', or "Knight Class", in-game) or as the "dungeon" itself (literally called the 'Bosses', or "Boss Class", in-game). What this means is that players can choose to play as the people invading the dungeon, or as the dungeon-holders themselves.
      Key Features:
      -Intense, fast-paced combat
      -Multiple skills, weapons, and ways to play the game
      -Tons of different Bosses, Minibosses, creatures and traps to utilize throughout the dungeon
      -Multiple unique environments
      -Interesting, detailed lore behind both the game and world
      -Intricate RPG system
      -Ladder and ranking system
      -Lots of customization for both classes s of customization for both classes
    • By RoKabium Games
      Custom coffee mugs have arrived... More caffeine!
      Have a great weekend everyone! 
      #gamedev #indiedev #sama #caffeine
  • Advertisement