- Home /
Question by
Kunaljani4536 · Oct 10, 2014 at 11:11 AM ·
positiontranslateoffset
Prefabs position gets changed
I am using this code to instantiate a prefab but after some cycles of code the position where prefab gets instantiate changes.This causes overlapping of prefabs. Like for first few x,y =1,1 later its different. I just want to move my prefab on z axis.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class MoveScript : MonoBehaviour {
public float objectSpeed = -0.5f;
public float posY = 0.0f;
public float posX = 0.0f;
public Transform prefab;
public LinkedList<Transform> roads = new LinkedList<Transform>();
private int numberOfRoads = 3;
void Start()
{
for(int i=0;i<numberOfRoads;i++)
{
Transform road = Instantiate(prefab) as Transform;
road.Translate(posX, posY, i* road.localScale.z);
roads.AddLast(road);
}
}
void Update()
{
Transform firstRoad = roads.First.Value;
Transform lastRoad = roads.Last.Value;
if(firstRoad.localPosition.z < -5f)
{
roads.Remove(firstRoad);
Destroy(firstRoad.gameObject);
Transform newRoad = Instantiate(prefab, new Vector3(posX,posY,lastRoad.localPosition.z + lastRoad.localScale.z), Quaternion.identity)as Transform;
roads.AddLast(newRoad);
}
foreach(Transform road in roads){
road.Translate(0,0,-8f*Time.deltaTime);
}
}
}
Comment