Code works but getting 3 Exceptions. Weird!

Hey guys! Long time listener, first time caller.

Actually, this is the first time I venture out from doing beginner Unity tutorials to trying to do my RPG’s XML-based story-loading architecture.

I’ve got my XML, the Deserialized class that maps to it, the Loader class that goes to get the right XML “node” if you will (not sure if that’s the best way to do -that- but…)

And then there’s my GameManager that keeps track of what storyNode we’re at and checks for player input to go to the next one.

Everything’s working great when I test in playmode!.. So why is Unity giving me 3 damned Exceptions!?

  1. UnityException: You are not allowed to call this function when declaring a variable.
  2. Internal_CreateGameObject can only be called from the main thread.
  3. ArgumentException: Internal_CreateGameObject can only be called from the main thread.

I can normally figure out its complaints when there’s a line number and stuff isn’t working, but now I’m stumped.

I’d appreciate some feedback from you benevolent souls.

using UnityEngine;
using System.Collections;

public class GameManager : MonoBehaviour {

int currentStoryNode = 1;
int nextStoryNode = 1; // to be updated in Update
bool playerAction = false;

DeserializedStoryNodesLoader storyNodeLoader = new DeserializedStoryNodesLoader();
DeserializedStoryNodes.StoryNode storyNode;
/* main image sprite holder */
public static Object main_image_prefab = new Object();
GameObject main_image= new GameObject();

void Start () {
	main_image_prefab = Resources.Load("Prefabs/main_image");
	main_image = Instantiate(main_image_prefab) as GameObject;
	storyNode = storyNodeLoader.generateNode (currentStoryNode);

	SetStoryImage(main_image, storyNode.get_img());

void Update () {
	if (Input.GetKeyDown("space") || Input.GetKeyDown("return")){
		playerAction = true;
	if (playerAction) {
		Debug.Log("Player has acted");

		// Get what's next (TODO: add answers check)
		int next_node =;
		currentStoryNode = next_node;

		// Fetch next node //
		storyNode = storyNodeLoader.generateNode (currentStoryNode);
		SetStoryImage(main_image, storyNode.get_img());

		playerAction = false;

void SetStoryImage (GameObject main_image, string new_img)
	Sprite newSprite = Resources.Load(new_img, typeof(Sprite)) as Sprite;
	if (newSprite == null) {
		Debug.Log("Problem loading image...");
	main_image.GetComponent<SpriteRenderer>().sprite = newSprite;


This line

GameObject main_image= new GameObject();

You can’t call new on a GameObject during initialisation. Try doing it this way.

GameObject main_image;

void Awake (){
    main_image = new GameObject();