You are creating new GameObject
s in your script (up
, down
, etc.) that have no relation to the objects you created in the editor. There are two solutions to this:
1) You need to assign up
, down
, etc. to the GameObject
s you created in the editor. You can do this by editing your Start
method to include:
up = GameObject.Find( "up" );
down = GameObject.Find( "down" );
// etc.
Replacing "up"
with whatever you named the up
GameObject
in the editor.
2) Assign up
, down
, etc. as children to your parent GameObject
using
up.transform.parent = parentGameObject.transform;
down.transform.parent = parentGameObject.transform;
// etc.
Note that if you go this route, then the up
, down
, etc. objects you made in the editor will not be used. You also will need to translate the new objects (after setting their parent) or else they will just sit at (0,0,0)
relative to the parent.
Edit in response to the comments
If I am understanding the problem correctly, then it seems you are just making a mistake in how you add the up
, down
, etc. objects as children in the editor. Simply drag them all onto the parent at the same level:
Then whenever the TestParent
object moves, the other objects stay at the same relative position to the parent, and thus move as well. Then if you add the GameObjects
to a script like so:
You can move the objects individually (while still being relative to the parent). With the following example script, the parent object moves up (Y+) at one unit a second. The Down
object also moves up at an additional one unit per second. This results in the ParentTest
, Up
, Left
, Right
maintaining formation, moving one unit per second up, while Down
moves at two units per second and slowly moves past them.
using UnityEngine;
using System.Collections;
public class DeleteMe : MonoBehaviour
{
public GameObject Up;
public GameObject Down;
public GameObject Left;
public GameObject Right;
void Start( )
{
}
// Update is called once per frame
void Update( )
{
Move( gameObject );
Move( Down );
}
private void Move( GameObject obj )
{
Vector3 position = obj.transform.position;
position.y += UnityEngine.Time.deltaTime;
obj.transform.position = position;
}
}
A screenshot of them at the start:
Another after some time has elapsed:
Finally note that you do not need to have public
GameObject
s in the script and then drag-and-drop them onto the script to access children. The same result can be achieved by modifying the script to:
private GameObject Up;
private GameObject Down;
private GameObject Left;
private GameObject Right;
void Start( )
{
Up = transform.Find( "Up" ).gameObject;
Down = transform.Find( "Down" ).gameObject;
Left = transform.Find( "Left" ).gameObject;
Right = transform.Find( "Right" ).gameObject;
}
This prevents the tedious nature of having to drag-and-drop onto the script itself, and also allows you to access children that may be added to the parent dynamically, and thus unable to drag-and-drop.
Hope this has helped!