I am working on a unity3d project which contains 3 scenes.
I have a very basic web server written in C# in this project.
This C# class is attached as a compontent of the first scene.
This first scene is the scene we see when the application runs.
Here is what i want to do: I want to change the scene when a user call a specific URL.
I am using this code in my http server:
SceneManager.LoadScene ("scene name");
I had an error because LoadScene should be called on main thread only. So i have made some changes in order to put scene name in a variable.
Then, i call LoadScene in Update() method from this variable value. I do not know if it is a good thing.
I have no error but the scene is not changing in game.
Thanks
** EDIT **
Here is my source code:
This first class is not associated to any scene (components):
public class ServeurWeb
{
private Scene1 main;
public ServeurWeb (Scene1 main)
{
this.main = main;
var newThread = new Thread(thread_serveur_web);
newThread.Start();
}
private void thread_serveur_web()
{
var listener = new HttpListener();
listener.Prefixes.Add("http://*:8084/");
listener.Start();
while (true)
{
try
{
var context = listener.GetContext();
ThreadPool.QueueUserWorkItem(o => HandleRequest(context));
}
catch (Exception)
{
}
}
}
private void HandleRequest(object state)
{
try
{
var context = (HttpListenerContext)state;
if (context.Request.Url.AbsolutePath=="/scene1")
{
main.load_scene("scene1");
}
if (context.Request.Url.AbsolutePath=="/scene2")
{
main.load_scene("scene2");
}
if (context.Request.Url.AbsolutePath=="/scene3")
{
main.load_scene("scene3");
}
context.Response.StatusCode = 200;
var buffer = System.Text.Encoding.UTF8.GetBytes("Hello!");
context.Response.ContentLength64 = buffer.Length;
var output = context.Response.OutputStream;
output.Write(buffer, 0, buffer.Length);
output.Close();
}
catch (Exception)
{
}
}
}
This second class is attached as a component to the scene1, in a gameobject:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Scene1 : MonoBehaviour {
private ServeurWeb serveur;
private string scene_active = "ecran_noir";
public void load_scene(string scene)
{
this.scene_active = scene;
}
void Start () {
serveur = new ServeurWeb (this);
}
void Update () {
if (SceneManager.GetActiveScene ().name != scene_active) {
SceneManager.LoadScene (scene_active);
}
}
}
When i run the project, i see Scene1. If i call http://localhost:8084/scene2 in my browser, i can see scene2. But, next, if i call any url, i can see a response in my browser (thread is alive), but scene2 stays on the screen
Thanks