Hi everyone, I started Unity and C# by the same occasion like two days ago, and I got an issue with a stackoverflow when I try to instantiate a prefabs.
Everything was working juste fine but then I tried to be clean by seperate things into different class/interface and then the problem occured.
Here is the differents part :
public class Game : MonoBehaviour
{
public ILevel level;
public void Start()
{
this.level = GameObject.FindWithTag("MainCamera").GetComponent<ILevel>();
this.level.InitBoard();
}
}
public interface ILevel
{
Tile FindTileByPosition(float x, float y);
void InitBoard();
List<PlayerScript> InitPlayer();
}
public class Level01 : MonoBehaviour, ILevel
{
private List<float[]> levelParameter;
void Start()
{
this.levelParameter = new List<float[]>
{
new float[] { 1, 1, 1, 1, 1.5F, 2 },
new float[] { 1, 1, 1, 1, 1, 2 },
new float[] { 1, 1, 1, 1, 1, 1 },
new float[] { 1, 1, 1, 1, 1, 1 },
new float[] { 1, 1, 1, 1, 1.5F, 2 },
new float[] { 2, 2, 2, 2, 2, 2 }
};
}
public void InitBoard()
{
Builder builder = GameObject.FindWithTag("MainCamera").GetComponent<Builder>();
if (builder.Init())
{
//this.lTile = builder.Build(this.levelParameter);
builder.Build(this.levelParameter);
}
}
[...]
}
public class Builder : MonoBehaviour
{
private GameObject prefabs1x1;
private GameObject prefabs2x1;
public bool Init()
{
this.prefabs1x1 = Resources.Load("Prefabs/1x1") as GameObject;
this.prefabs2x1 = Resources.Load("Prefabs/2x1") as GameObject;
if (this.prefabs1x1 == null || this.prefabs2x1 == null)
{
Debug.Log("IT'S NULL!!!");
return false;
}
return true;
}
//public List<Tile> Build(List<float[]> map)
public void Build(List<float[]> map)
{
float x = 0;
float z = 0;
//List<Tile> lTile = new List<Tile>();
foreach (float[] ligne in map)
{
foreach (float height in ligne)
{
if (height == 1)
{
//lTile.Add(Instantiate(this.prefabs1x1, new Vector3(x, 0.5F, z), Quaternion.identity).GetComponent<Tile>());
Instantiate(this.prefabs1x1, new Vector3(x, 0.5F, z), Quaternion.identity);
}
else
{
//lTile.Add(Instantiate(this.prefabs2x1, new Vector3(x, 0.5F, z), Quaternion.identity).GetComponent<Tile>());
Instantiate(this.prefabs2x1, new Vector3(x, 0.5F, z), Quaternion.identity);
}
x++;
}
x = 0;
z++;
}
//return lTile;
}
At first Unity just crashed every time I was launching the game but some rare time the console had time to show a stackoverflow error before unity crash.
I’m confused because it’s work just fine when I comment the instantiate line.
Sorry for the long post.