如何统一检查最近物体的颜色?
Posted
技术标签:
【中文标题】如何统一检查最近物体的颜色?【英文标题】:How can i check the color of the closest object in unity? 【发布时间】:2021-03-01 20:33:15 【问题描述】:我有这个游戏https://play.google.com/store/apps/details?id=com.nbstudio.towercolor&hl=ru 中的逻辑。他们有逻辑,当球撞击并接触圆柱体时,如果附近的物体与球的颜色相同,它就被摧毁了。我尝试制作一个在播放模式运行时生成的对象的二维数组,但我不知道如何检查对象的颜色。
public class DestroingObjects : MonoBehaviour
[SerializeField]
private List<GameObject> objects;
public GameObject[,] game;
public GameObject[] gameObjects;
[SerializeField]
private float timeLeft;
[SerializeField]
GameObject prefab;
[SerializeField]
Material colorOfPlayer;
[SerializeField]
MeshRenderer[,] mesh;
[SerializeField]
private TowerCreator tower;
// Start is called before the first frame update
void Start()
tower = FindObjectOfType<TowerCreator>();
// Update is called once per frame
void Update()
timeLeft -= Time.deltaTime;
if (timeLeft < 0)
timeLeft = 1;
gameObjects = GameObject.FindGameObjectsWithTag("Object");
game = new GameObject[tower.pieceCount, tower.levelsOfTowerCount];
for (int i = 0; i < tower.pieceCount; i++)
for (int j = 0; j < tower.levelsOfTowerCount; j++)
game[i, j] = gameObjects[i];
Debug.Log(game.Length);
findColors();
public void findColors()
for (int i = 0; i < tower.pieceCount; i++)
for (int j = 0; j < tower.levelsOfTowerCount; j++)
var mesh = game[i, j].GetComponent<MeshRenderer>();
Debug.Log(mesh.material.color);
【问题讨论】:
【参考方案1】:您不想检查对象的“物理”颜色(如Renderer
所示)。您需要的是一个包含游戏中所有可用颜色的 enum,因为您想将它们用作标识符:
public enum MyColor
Red,
Green,
Blue
public class Ball : MonoBehaviour
public MyColor BallColor;
public class Cylinder : MonoBehaviour
[SerializeField] private MyColor myColor;
private void Start()
// set the renderers color ("physical" color) to a desired rgb value
GetComponent<MeshRenderer>().material.color = TranslateEnumToColor(myColor);
private static Color TranslateEnumToColor(MyColor c)
...
...
// call this, when ball hits cylinder
public void BallHitMe(Ball theHittingBall)
if(theHittingBall.BallColor == myColor)
Debug.Log("colors do match, destroy me now");
通过这种方式,您可以获得颜色标识符 (MyColor),而不必担心 Renderer
(或纹理,如果您想在未来添加更精美的东西)之类的东西。
【讨论】:
【参考方案2】:当您检查 objects.color 时,它会检查多个浮点数
.color 是 color(r,g,b,a) red, green,blue,alpha 因此,如果要显示为调试,则需要将其进一步缩小到其值: Debug.log("r="+spriteRenderer.color.r +" g="+ spriteRenderer.color.g +" b="+ spriteRenderer.color.b);
【讨论】:
以上是关于如何统一检查最近物体的颜色?的主要内容,如果未能解决你的问题,请参考以下文章