[英]C# - How do I have 2 gameobjects ALWAYS have the same y values in unity
I currently have a cube in my scene that I have moved around. 我目前在我的场景中有一个立方体,我已经四处移动了。 And I want another cube to always have the same y value. 我希望另一个立方体始终具有相同的y值。 So if the first cube moved down 10 units I want the other to do the same. 因此,如果第一个立方体向下移动10个单位,我希望另一个立方体做同样的事情。
My first cube was manually created in the editor, but my other one is placed using scripts. 我的第一个多维数据集是在编辑器中手动创建的,但我的另一个是使用脚本放置的。 Thanks! 谢谢!
You could as already said use a parent child relation, but then every movement of the parent will cause movement on the child for x, y and z coordinates. 您可以如已经说过的那样使用父子关系,但是父母的每次移动都会导致孩子在x,y和z坐标上移动。
If you want the other object follow only the y coordinate and not the others, then you cannot use a parent-child relationship for that. 如果您希望其他对象仅遵循y坐标而不是其他对象,则不能使用父子关系。
Instead, you could use a script (inspiration from : https://answers.unity.com/questions/543461/object-follow-another-object-on-the-x-axis.html ) 相反,您可以使用脚本(灵感来自: https : //answers.unity.com/questions/543461/object-follow-another-object-on-the-x-axis.html )
using UnityEngine;
using System.Collections;
public class SameYCoordinateAsOther : MonoBehaviour {
Transform otherTransform;
void Start() {
// you can set a reference to the "parent" cube
otherTransform = GameObject.Find("cube1").transform;
}
void Update() {
// here we force the position of the current object to have the same y as the parent
transform.position = new Vector3(transform.position.x, otherTransform.position.y, transform.position.z);
}
}
And you just attach this script to any object that must 'follow' the first cube on the y-axis. 您只需将此脚本附加到必须“跟随”y轴上的第一个立方体的任何对象。
This script will force the second object to have the same y-value of the first. 此脚本将强制第二个对象具有与第一个对象相同的y值。
If you do not want them to have the same values, but only that the amount of of movement is the same, this will be a bit more complicated. 如果您不希望它们具有相同的值,但只是移动量相同,则会更复杂一些。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.