- Home /
How do i have multiple objects to rely on a objects position?
How do i have multiple objects to rely on a objects position, for an example, every of the objects rely on the main objects position kind of like whats in the picture below if i only move the red cube the rest of the other cubes follow the red cube, i know this can be done if i set the other cubes as child's of the red cube but i don't want to it like that i just want it through script, would anyone know how to do this?
Answer by wesleywh · Aug 09, 2016 at 01:16 AM
Adding it as a child would be easiest. The other thing I can think of would be to offset your x,y,z coordinates by that of the red cube. Example you could have a public offset that is available to everyone. Make a script like the following on the red cude (Example script named "PositionScript"):
public Vector3 offset = Vector3.zero;
private Vector3 originalPos = Vector3.zero;
void Start()
{
originalPos = this.transform.position;
}
void Update()
{
offset.x = this.transform.position.x - originalPos.x;
offset.y = this.transform.position.y - originalPos.y;
offset.z = this.transform.position.z - originalPos.z;
}
Then have something like this on the grey cubes:
void Update()
{
this.transform.position = this.transform.position - GameObject.FindGameObjectByTag("redcube").GetComponent<PositionScript>().offset;
}
Please note that none of these are actually tested to see what they do but the general idea is there. To get the same effect you can place it as a child (A lot easier):
this.transform.parent = GameObject.FindGameObjectByTag("redcube");
Then remove it when you don't want it to follow anymore:
this.transform.parent = null;
Ya sure. I just added tags because it is probably the next easiest thing to do. You could do it by the objects name.
GameObject.Find("$$anonymous$$yRedCube").GetComponent<PositionScript>().offset
I have to ask though, why not a tag or parent child relationship? You can have essentially unlimited tags. Name isn't the best way because you might forget what you named your object from one scene to another. I can't think of any other reliable way to get your object. The only other object finder is by object type. That won't work though because all the types here are going to be the same.
I just thought of another way actually. You could find the object with the PositionScript attached. (This goes along with my type idea):
GameObject.FindObjectsOfType(typeof(PositionScript))
$$anonymous$$ore on this at this answer:
http://answers.unity3d.com/questions/527447/find-gameobjects-with-a-certain-script.html