C# - 我如何让 2 个游戏对象在统一中始终具有相同的 y 值

标签 c# unity3d

我目前在我的场景中有一个立方体,我已经四处移动了。我希望另一个立方体始终具有相同的 y 值。因此,如果第一个立方体向下移动 10 个单位,我希望另一个立方体也这样做。

我的第一个立方体是在编辑器中手动创建的,但我的另一个立方体是使用脚本放置的。谢谢!

最佳答案

如前所述,您可以使用父子关系,但是父子关系的每一次移动都会导致子对象在 x、y 和 z 坐标上发生移动。

如果您希望其他对象遵循 y 坐标而不是其他对象,那么您不能为此使用父子关系。

相反,您可以使用脚本(灵感来自: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);
     }
}

您只需将此脚本附加到任何必须“跟随”y 轴上第一个立方体的对象。

此脚本将强制第二个对象具有与第一个对象相同的 y 值。

如果您希望它们具有相同的值,但只是移动量相同,这会有点复杂。

关于C# - 我如何让 2 个游戏对象在统一中始终具有相同的 y 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49848372/

相关文章:

c# - 仅接受波斯字符的正则表达式

javascript - 如何将数据从 .NET Controller 显示到 React View ?

c# - Windows Phone 8 列表框

c# - 扩展方法中的协程

c# - Unity Raycast 问题

c# - 派生类的构造函数可以比其基类的构造函数有更多的参数吗?

c# - 升级到 Web API 2 后,HttpApplication.Application_Start 未触发

c# - 使用 Json.Net 从流反序列化时如何设置自定义日期格式

unity3d - 为什么我的粒子系统碰撞不起作用?

c# - 使用静态时出现 "An object reference is required to access non-static member"错误