我有 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 个浮点值,因此如果要输出“颜色为红色”或“颜色为蓝色”,则需要进行等价检查,就像我在上面提供的“// 做某事”注释中一样。
- 1 回答
- 0 关注
- 105 浏览
添加回答
举报
0/150
提交
取消