- Home /
How do i Instantiate sub-Points with in Multiple Points??
Hello i am having trouble trying to make sub-Points(RedSphere) with in Points(Cube) and then add the
sub-Points(RedSphere) as childs to the Points(Cube), so i can move a Cube with its Sub-Points(Redsphere) attached to it, see in Pic1 so you know what i mean exactly. And here are the results i am getting which is in Pic2, does anyone know how to do this.
-Pic1 (i randomized the Cubes so you can tell what i mean) -Pic2 (The results i am getting with the code Below) And Here is the code so you know what i have done.
using UnityEngine;
using System.Collections;
public class Points : MonoBehaviour {
private Vector3[] cubePoints;
private Vector3[] spherePoints;
public GameObject cubePrefab;
public GameObject spherePrefab;
public int cubeAmount, sphereAmount, offset;
void Start()
{
cubePoints = new Vector3[(cubeAmount + 1)];
for (int i = 0, x = 0; x <= cubeAmount; i++, x++)
{
cubePoints[i] = new Vector3(x * offset, 0);
Instantiate(cubePrefab, cubePoints[i], Quaternion.identity);
}
spherePoints = new Vector3[(sphereAmount + 1)];
for (int i = 0, z = 0; z < sphereAmount; i++, z++)
{
spherePoints[i] = new Vector3(0, 0, z);
Vector3 position = spherePoints[i];
Instantiate(spherePrefab, position, Quaternion.identity);
position = cubePoints[i];
}
}
}
Answer by damagefilter · Aug 10, 2016 at 07:09 AM
You're almost there. Just a few things to adjust.
If you want the spheres to move along with the cubes, you'll have to parent them. For this you need to keep the reference Instantiate
returns (cast to GameObject) on line 19 (in the snippet)
var cube = Instantiate(cubePrefab, cubePoints[i], Quaternion.identity) as GameObject;
Then you need to instantiate the spheres for each of these cubes and parent them. So that'll be a nested for loop. Also you'll need to set the localPositionof these spheres (relative to their new parent)
Something like this:
cubePoints = new Vector3[(cubeAmount + 1)];
for (int i = 0, x = 0; x <= cubeAmount; i++, x++)
{
cubePoints[i] = new Vector3(x * offset, 0);
// need the cube for parenting spheres, keep it
var cube = Instantiate(cubePrefab, cubePoints[i], Quaternion.identity) as GameObject;
spherePoints = new Vector3[(sphereAmount + 1)];
for (int j = 0, z = 0; z < sphereAmount; j++, z++)
{
spherePoints[j] = new Vector3(0, 0, z+1); // +1 because otherwise the first sphere is within the parent cube
// You might want to track the sphere instead of the vec3?
var sphere = Instantiate(spherePrefab, Vector3.zero, Quaternion.identity) as GameObject;
// parent
sphere.transform.SetParent (cube.transform);
// do positioning relative to parent
sphere.transform.localPosition = spherePoints[j];;
}
}
That only works, of course, because the prefabs are exactly one unit deep on the z axis. If the prefabs were of different size you'd need to find that and use it for positioning instead.