# Unity CreateInstance can only be called from the main thread.

## Recommended Posts

FGFS    345

Hi
New to Unity and c# I get:

CreateInstance can only be called from the main thread.
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

Edited by FGFS

##### Share on other sites
SmkViper    5396
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 on other sites
ChaosEngine    5185

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 on other sites
Nypyren    12074
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 on other sites
FGFS    345

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 on other sites
rip-off    10979

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.

## Create an account

Register a new account

• ### Similar Content

• My first goal is to build in python a text-based (next version will have graphics) adventure game scenario where a player enters a tavern, and goes on a quest. Earns money, buys weapons and gets in a fight.

So I've got four ideas for games I want to build.
1. a space simulation where a mute evolving clique is tasked with colonising planets - it's also a social network.
My next goal is to build a 3rd person shooter and streets of rage style framework for a action/adventure game based on my story which is about God's mightiest heroes (with mutation sandbox) versus the devil (read pinhead meets bizarro superman).
I also want to build in python, a 3d isometric rpg/sim that looks like the sims 1 but thematically is more like Bully or GTA1, but plays like Hell's Kitchen DS combined with Dofus, with environments combining elements of Phantasy Star, Sonic and art photography of convenience stores, etc.
I also want to build an epic adventure story in RPGMakerMV.
Any advice as to what else I should build in between to get closer to my goal projects.

In a few weeks I'll have my first game, I'm not really sure how to turn it into an executable file so i can share it with people who don't have python installed.

• I've been using async-await in Unity 2017 for awhile now and went through some hurdles getting it to work properly with the unity way of doing things. In order to avoid anyone else suffering the same problems I've posted a tutorial with what I've learned here:

http://www.stevevermeulen.com/index.php/2017/09/23/using-async-await-in-unity3d-2017/

•
Hi, I would like to have an opinion on what I can improve and change in my first published game.
The game was made on Unity3D.
Thank you.

• You are a US Army soldier, and one day an unknown enemy attacked your base. Now your task is to survive and protect the base. There are a lot of weapons in your arsenal. Survive this nightmare at any cost.

• Hi,
I am composer and sound designer that is trying to learn some codeing  Could You help me and tell me what should i add to change volume to 1.0F when enter trigger
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AudioPlay : MonoBehaviour {

public AudioClip strings_1;
AudioSource audioSource;

// Use this for initialization
void Start () {
audioSource = GetComponent<AudioSource> ();
audioSource.PlayOneShot (strings_1, 0.0F );   - when game starts i want it to start but with 0 volume
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter2D (Collider2D other)
{
if(other.gameObject.tag == "slotviolin")
{
Debug.Log ("coilder works");

// how can i change volume to 1.0F and if it's possible how to make it smooth ?

}
}
}

Thanks

• 14
• 20
• 35
• 13
• 39