Instantiate commands creating infinite number of clones

public class TrapMaker : MonoBehaviour {

	public int trapSizeHorizontal = 5;
	public int trapSizeVertical = 5;
	public float trapCellWidth = 64.0f;
	public float trapCellHeight = 64.0f;
	
	public GameObject cell;
	
	void Start () {
		GameObject inst = null;

		Vector3 pos = transform.position + new Vector3(-1, -1, -0.1f);
		inst = (GameObject)Instantiate (cell, pos, Quaternion.identity);

    }

	void Update () {
	}
}

I only have these.
However, somehow when I play in main, it creates something like this under Hierarchy:

Trap(clone)
Trap(clone)(clone)
Trap(clone)(clone)(clone)
Trap(clone)(clone)(clone)(clone)
.
.
.
and so on.

If it is not the code, what could be the problem?

Thank you.

1 Answer

1

It looks like you have ‘cell’ initialized with the game object this script is attached to. Each time it Instantiates() a clone, the Start() of the clone is run creating a new copy. The new copy creates a copy, and so on. The fix would be to not have this script on the game object being cloned.

Thank for the reply. I thought so but whenever I move this script into somewhere that has a script and not keep creating clone; or I crate an empty hierarchy to store the scripte only and drag my prefab, it still creates multiple clones of clones. Since I am quite new to Unity and I am really confused. :(

I'm not sure of your setup, but start with a new scene. Attach this script to an empty game object. Make sure that whatever object you initialize 'cell' to does not have this script.

Is it possible to upload a zip file here?

Thanks a lot. You were right. I found it. It was from my prefab. It was my old prefab and I thought I took out the scripte but did not update the old one and it was duplicated every time. I was so dumb that I waste few hours just on this one. T_T Anywats, thx you so much.

Thank you very much ;)