Spawn a number of prefabs an equal distance apart
Hello All,
I have a script that looks at an int number (set by the user) and spawns that many prefabs on a button click. So far it works pretty well, but the prefabs all spawn on top of each other.
What do I need to add to make them spawn in a horizontal line?
Here's my functioning script C#:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SpawnMore : MonoBehaviour {
public GameObject prefab;
public int num = 1;
public GameObject NumObj;
private Text Numbers;
private float distance = 0.5f;
// Use this for initialization
void Start() {
Numbers = NumObj.GetComponent<Text>();
Numbers.text = num.ToString();
}
public void Add()
{
if (num < 9)
{
num += 1;
SetCountText();
}
else
{
return;
}
}
public void Subtract()
{
if (num > 1)
{
num -= 1;
SetCountText();
}
else {
return;
}
}
void SetCountText()
{
Numbers.text = num.ToString();
}
public void SpawnX()
{
Vector3 pos = Camera.main.transform.position;
Vector3 setRight = Camera.main.transform.right;
Vector3 setForward = Camera.main.transform.forward;
for (var i = 0; i < num; i++)
{
Instantiate(prefab, (pos + (setRight * distance) + setForward * 2), transform.rotation);
}
}
}
Answer by Fobri · Feb 01, 2017 at 12:41 PM
int offset = 0; for (var i = 0; i < num; i++) { Instantiate(prefab, (pos + (setRight * distance) + setForward * 2) + new Vector3(offset, 0, 0), transform.rotation); offset += 30; }
Should work, not tested tho. modify the offset value at the end of the loop to spawn them closer/further from each other.
Answer by repsacc · Feb 01, 2017 at 02:21 PM
You are spawning them in the same place. (pos + (setRight * distance) + setForward * 2)
never changes. Try the code below instead.
for (var i = 0; i < num; i++)
{
Instantiate(prefab, (pos + (setRight * distance) + setForward * i), transform.rotation);
}
This will spawn the objects further and further in away from the main camera, in the forward direction of the main camera.
Since he said "horizontal" i guess he ment on the x-axis as he already has a "distance" variable. So i guess he wants
(setRight * distance * i)
Your answer
Follow this Question
Related Questions
Trying to spawn enemies on only one path 1 Answer
instantiate capacity 0 Answers
How to do a Spawn Animation 1 Answer
Spawn Prefab based on int value 1 Answer
Im trying to set a spawned enemy a transform on another script 0 Answers