- Home /
How do i Instantiate gameObjects in between multiple points?
Hello i am having some trouble trying to instantiate GameObjects in between multiple points, but i am not getting the results that i want. This is what i am trying to achieve in Pic1, and the results i am getting in Pic2 if anyone know's how to do this?
Pic1 Pic2
Here is the code so you know what i have done
using UnityEngine;
using System.Collections;
public class Points : MonoBehaviour {
public Transform[] points;
public GameObject GameObj;
public float GameObjectAmount = 2;
void Start () {
for (int i = 0; i < points.Length; i++)
Instantiate(GameObj, points[i].position / GameObjectAmount, Quaternion.identity);
}
}
Answer by StupidlySimple · Aug 07, 2016 at 06:43 AM
// Yawn... Probably something like this. Didn't test it because... well, I'm working on my game at the moment and didn't want to clear the current scene for you :P
public class Points : MonoBehaviour
{
public Transform[] points; // I'm assuming this is coordinate of all your sugar cube.
public GameObject GameObj; // Object you want to duplicate
public float GameObjectAmount = 2; // Why is this float, you cannot have "half" a game object ;)
void Start()
{
duplicateObject(GameObj, (int) GameObjectAmount);
}
public void duplicateObject(GameObject original, int howmany)
{
howmany++; // Because Logic!
for (int i = 0; i < points.Length-1; i++)
{
for (int j = 1; j < howmany; j++)
{
Vector3 position = points[i].position + j * (points[i + 1].position - points[i].position) / howmany; // Because Logic!
Instantiate(original, position, Quaternion.identity);
}
}
}
}
By the way how i would i do this for void Update ? i'm a rookie at c# if you know any good tutorials on stuff like this i would like to know, Thanks again.
No idea what's you're asking for.
If you want this function inside Update(), you will crash your game as it will generate a bunch of gameObjects every frame that Update is being called. o_O?
void Update()
{
duplicateObject(GameObj, (int) GameObjectAmount);
}
I know, but is there a way to generate it once, so i can position it where ever?
Answer by breban1 · Aug 07, 2016 at 11:26 AM
I'm not sure what you are trying to do with the calculation:
points[i].position / GameObjectAmount
But it looks wrong to me.
If I am reading your question correctly, I THINK you want to instantiate between the points...
for (int i = 0; i < points.Length-1; i++)
{
Instantiate(GameObj, Mathf.Lerp(points[i].position, points[i].position, .5f), Quaternion.identity);
}
Note the points.Lenght-1 in the loop, you'll need that or you will go out of bounds.