Hello everyone,
I don’t get how prefab instantiation works.
I’m coding a 2d vertical infinite scrolling and I made a script that continually create new tiles of background (prefab) at top and destroy itself when its at bottom.
Then each background instantiate a group of windows (prefab too). Later some window would be animated or scripted or whatever so it is important that each window is a different gameObject.
The problem is, each background seems to herit windows from the last background created. So 1st bacnkground has 3 windows, 2nd has 6, 3rd has 9… etc…
[29153-screen+shot+2014-07-13+at+15.28.37.png|29153]
like if all child were cloned too… but they dont exist in the prefab, I create them at runtime…
I’m sure I’m not using those prefabs the good way but that is my first Unity Project I don’t how to handle the all-situation so if you have any clue…
here’s my code :
using UnityEngine;
using System.Collections;
public class bg_parallax : MonoBehaviour
{
static public Vector2 speed = new Vector2 (5, 5);
static public Vector2 direction = new Vector2 (0, -1);
public GameObject background;
public GameObject window;
private bool needChild = true;
// Use this for initialization
void Start ()
{
((GameObject)Instantiate (window, new Vector3 (-1.8f, -1.5f, 19f), transform.rotation)).transform.parent = transform;
((GameObject)Instantiate (window, new Vector3 (0f, -1.5f, 19f), transform.rotation)).transform.parent = transform;
((GameObject)Instantiate (window, new Vector3 (1.8f, -1.5f, 19f), transform.rotation)).transform.parent = transform;
}
// Update is called once per frame
void Update ()
{
}
void FixedUpdate ()
{
transform.Translate (new Vector3 (speed.x * direction.x, speed.y * direction.y, 0) * Time.deltaTime);
if (needChild && transform.position.y <= 0) {
((GameObject)Instantiate (background, new Vector3 (0, transform.position.y + renderer.bounds.size.y, 20), transform.rotation)).transform.parent = transform.parent;
needChild = false;
}
if (transform.position.y <= renderer.bounds.size.y * -1)
{
for(int i = 0; i < transform.childCount; i++)
DestroyImmediate(transform.GetChild(i).gameObject);
Destroy (gameObject);
}
}
}