- Home /
The question is answered, right answer was accepted
How to instantiate Road Prefab at desired position ?
Hello everyone I have successfully written script for road generation and it works perfectly but I want to instantiate Road Prefab at my desired x position please help me if anyone knows Here is the script:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class RoadGenerator : MonoBehaviour {
private float spawnz = -6f;
public GameObject[] prefabs;
private float RoadLength = 109.4f;
private int amountOfRoads = 6;
private List<GameObject> roadsList;
private Transform playertransform;
void Start () {
roadsList = new List<GameObject>();
playertransform = GameObject.FindGameObjectWithTag("Player").transform;
for (int i = 0; i < amountOfRoads; ++i)
SpawnRoad(0);
}
void Update () {
if (playertransform.position.z > (spawnz - amountOfRoads * RoadLength))
{
SpawnRoad(0);
DeleteRoad();
}
}
void SpawnRoad(int prefabIndex)
{
GameObject go;
go = Instantiate(prefabs[prefabIndex]) as GameObject;
go.transform.SetParent(transform);
go.transform.position = Vector3.forward * (spawnz - 109.4f);
spawnz += RoadLength;
//adding gameobject to list
roadsList.Add(go);
}
void DeleteRoad () {
Destroy(roadsList[0]);
roadsList.RemoveAt(0);
}
Answer by pauldarius98 · Mar 01, 2021 at 10:03 AM
Could you provide more information, like what is going wrong? Do you have errors or the roads are spawning at the same position?
Yes of course I have a ground which is at 0 x position and a player which is also at 0 x position but the player is on the left side of the ground and I have attached a swipe manager script to the player the problem is that the swipe function also starts from the left side of the ground and I want to spawn my ground according to the player such that the player should be in the middle of the ground please tell me that how can I change the x position of the ground which is to be instantiated ?
Roads are spawning perfectly but I want to spawn the ground at these positions (-5.54, 0, 0)
Oh, I see. In that case the solution is quite easy, at line 32 you should have:
go.transform.position = new Vector3(x, 0, spawnz - 109.4f);
And instead of x place the value that you need
Thanks sir this line of code is working fine but I did not replace this line on the line number 32 instead I did write this line after line number 32
go.transform.position = new Vector3(x, 0, spawnz - 109.4f);
Follow this Question
Related Questions
Junior Programming Pathway scaling a cube 2 Answers
Trying to find the highest number than add it to itself. 2 Answers
Having trouble using SendMessage 1 Answer
Help with falling enemy Unity 3D 0 Answers
Point Counter Works Only Once! 1 Answer