为了账号安全,请及时绑定邮箱和手机立即绑定

如何让一个游戏对象定位其他游戏对象的位置并告诉它们的颜色?

如何让一个游戏对象定位其他游戏对象的位置并告诉它们的颜色?

C#
哔哔one 2022-11-13 15:52:40
我有 2 个游戏对象,一个蓝色和一个红色。两人都在场景中跑来跑去,镜头受限,所以他们不能通过某个区域。如果可能的话,我也想知道如何在对角线上移动它们。这是我的全部代码。public Transform Objectup;public Transform Objectdown;public Transform Objectright;public Transform Objectleft;public DirectionGameObject direction;public int speed = 2;public enum DirectionGameObject{    Right,    Left,    Up,    Down}// Start is called before the first frame updatevoid Start(){    direction = SortdirectionGameObject(direction);}// Update is called once per framevoid Update(){    Destroy();    if(direction == DirectionGameObject.Right)    {        transform.Translate(Vector3.right * Time.deltaTime * speed);        if(transform.position.x >= Objectright.position.x)        {            direction = SortdirectionGameObject(direction);        }    }    if(direction == DirectionGameObject.Left)    {        transform.Translate(Vector3.left * Time.deltaTime * speed);        if(transform.position.x <= Objectleft.position.x)        {            direction = SortdirectionGameObject(direction);        }    }    if(direction == DirectionGameObject.Up)    {        transform.Translate(Vector3.up * Time.deltaTime * speed);        if(transform.position.y >= Objectup.position.y)        {            direction = SortdirectionGameObject(direction);        }    }    if(direction == DirectionGameObject.Down)    {        transform.Translate(Vector3.down * Time.deltaTime * speed);        if(transform.position.y <= Objectdown.position.y)        {            direction = SortdirectionGameObject(direction);        }    }}private DirectionGameObject SortdirectionGameObject(DirectionGameObject maindirection){    DirectionGameObject directionSorted = maindirection;    do{        int newDirection = Random.Range((int)DirectionGameObject.Right, (int)DirectionGameObject.Down + 1);        directionSorted = (DirectionGameObject)newDirection;    } while (maindirection == directionSorted);    return directionSorted;}void Destroy(){    Destroy(gameObject,120.0f);}当我按下 G 和 V 时,我需要在控制台上显示它们的颜色和位置。C#unity3d
查看完整描述

1 回答

?
守候你守候我

TA贡献1802条经验 获得超10个赞

您要查找的游戏对象的颜色属性位于渲染器组件的材质中。


可以这样引用:


gameObject.GetComponent<Renderer>().material.color

为了获得 GameObject 的 Renderer 组件,您必须拥有对它的引用,例如:


GameObject object1;

GameObject object2;

然后,您可以像这样获取每个对象的颜色:


Color color1 = object1.GetComponent<Renderer>().material.color;

然后你可以像这样检查颜色的值:


if (color1 == Color.red){


    // Do something


}

或者,如果你想在控制台显示它们的颜色:


Debug.Log(color1);

颜色存储为 4 个浮点值,因此如果要输出“颜色为红色”或“颜色为蓝色”,则需要进行等价检查,就像我在上面提供的“// 做某事”注释中一样。


查看完整回答
反对 回复 2022-11-13
  • 1 回答
  • 0 关注
  • 87 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信