【问题标题】:If 3 game objects are the same color, how can I destroy them? [closed]如果 3 个游戏对象颜色相同,我该如何销毁它们? [关闭]
【发布时间】:2022-06-10 22:05:29
【问题描述】:

我是统一的新手。 我正在尝试制作像立方体匹配这样的游戏。在这里,如果三个立方体颜色相同,我想检测它并从场景中删除立方体,我该怎么做?

如果收集到的三个方块颜色相同,我想销毁它们

【问题讨论】:

  • 比较颜色,如果匹配,通过Object.Destroy 或其他方式将其删除?

标签: c# unity3d


【解决方案1】:

您需要在立方体本身或某个主对象中存储有关颜色的某种信息,但我认为将其存储在立方体中会更好。

//Example of a 'Cube.cs' script
//Also I left out the 'using' tags for simplicity
public class Cube : MonoBehaviour
{
    public enum m_Color
    {
        Red,
        Yellow,
        Green
    }
    public m_Color cubeColor = Color.Red;

}

然后你需要从你的相机射出一条射线并存储你击中的物体,以便在点击其中三个时比较它们的数据:

//Again Example code without 'using' tags
public class MasterObj : MonoBehaviour
{
    Cube[3] cubes;
    int currIndex = 0;
    public Camera cam;
    
    void Update()
    {
        RaycastHit hit;
        if(Physics.Raycast(cam.ScreenPointToRay(Input.mousePosition), out hit))
        {
            cubes[currIndex] = hit.gameObject.GetComponent<Cube>();
            
            if(currIndex == 2)
            {
                currIndex = 0;
                if(cubes[0].cubeColor == cubes[1].cubeColor && cube[0].cubeColor == cubes[2].cubeColor && cubes[2].cubeColor == cubes[1].cubeColor)
                {
                    Debug.Log("Found a matching pair!");
                    Destroy(cube[0].gameObject);
                    Destroy(cube[1].gameObject);
                    Destroy(cube[2].gameObject);
                }else{
                    Debug.Log("Not matching");
                }
            }else{
                currIndex++;
            }
        }
    }
}

这很简单,可能行不通(但如果你愿意,你仍然可以尝试),只是为了展示你自己如何做到这一点。如果您想使用它,我建议您将其输入下来,因为这将有助于记住呼叫。

【讨论】:

    【解决方案2】:

    如果您一般想获取所有或其中的一部分并找到特定颜色,您可以using System.Linq,如下所示。

    var blueCubes = FindObjectsOfType<MeshRenderer>().Where(m => m.material.color == Color.blue);
    

    例如,此代码删除三个蓝色立方体(如果有)。

    if (blueCubes.Count() == 3) blueCubes.ForEach(m => Destroy(m.gameObject));
    

    通过使用ToLookup,您还可以按颜色对立方体进行分类。

    public Color blue;
    public Color red;
    void Start()
    {
        var cubes = FindObjectsOfType<MeshRenderer>().ToLookup(m => m.material.color);
    
        Debug.Log("Blue: "+cubes[blue].Count()); // blue cubes count
        
        Debug.Log("Red: "+cubes[red].Count()); // red cubes count
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多