- Home /
Instantiating Prefab fails but no error message
Hi all,
I have an issue instantiating prefabs. I generate tiles for my game and I want to display an effect (the prefab) on top of each tile. I tried everything I could think off. The prefab is recognized as a gameobject (I checked using Debug.Log) I can also execute code before and after without any problem.
The prefab is in a singleton and that seems to be causing some problems. Anybody came across this before ? This is my singleton which contains an array of GameObject with my prefabs : infoSkins
public class TileManager : MonoBehaviour {
public GameObject[] infoSkins;
#region
//Awake is always called before any Start functions
void Awake()
{
//Check if instance already exists
if (instance == null)
//if not, set instance to this
instance = this;
//If instance already exists and it's not this:
else if (instance != this)
//Then destroy this. This enforces our singleton pattern, meaning there can only ever be one instance of a GameManager.
Destroy(gameObject);
}
#endregion //Singleton setup
I then call this method when the game starts:
public void Initialise(Vector2 currentPos, int row, int col){
pos = currentPos;
InstantiateInfoVFX();
}
public void InstantiateInfoVFX()
{
if (targetCategory.type == "Fire")
{
GameObject.Instantiate(TileManager.instance.infoSkins[0], new Vector3(pos.x, 0.3f, pos.y), Quaternion.identity); //This is not working, no objects is added to the hierachy
Debug.Log("TEST"); //this however prints and the game runs fine
}
}
Answer by ghostmode · Oct 13, 2017 at 07:04 AM
Can you check if the prefab you're instantiating from is null. Also, you may as well check the instance while you're at it. I know you said you already checked something similar, but this really helps a lot to narrow things down.
var prefab = TileManager.instance.infoSkins[0];
if (prefab == null) {
Debug.Log("the prefab is NULL!");
} else {
Debug.Log("the prefab is NOT null");
}
var instance = Instantiate(prefab, new Vector3(pos.x, 0.3f, pos.y), Quaternion.identity);
if (instance == null) {
Debug.Log("the instance is NULL!");
} else {
Debug.Log("the instance is NOT null");
}
Edit: Another thought, you might have 2 instances of your singleton, one of which is being quietly destroyed. Replace your tile manager's Awake with the following:
private void Awake() {
if (instance == null) {
instance = this;
} else {
Debug.LogError("Found multiple TileManagers! Destroying instance.");
Destroy(gameObject);
}
}
This will show an error when you accidentally have multiple tile managers in your scene.
thank you for the reply. I checked that the prefab is not null. It does return a GameObject. I will try out the multiple Singleton fix tonight though !