在Unity中单击时如何更改游戏对象的颜色?

时间:2019-03-18 22:29:13

标签: c# unity3d sprite hexagonal-tiles

我正在尝试创建棋盘游戏十六进制。底部的第一名玩家是黄色,顶部的第二名玩家是蓝色。当玩家一单击一个十六进制时,它应变为黄色,而当玩家二单击一个十六进制时,则应变为蓝色。

我已经使用预制件创建了此Hex Map,现在我希望能够在单击时更改每个瓦片的颜色(您看到的黄色十六进制将是透明的,但我导入的精灵为黄色,即为什么即使六边形看起来是黄色,Sprite Renderer上的颜色还是白色)。

顺便说一句,到目前为止,在Sprite Renderer中更改颜色会更改所有十六进制的颜色。

我遵循quill18creates的教程制作了十六进制贴图,除了我以2D而不是3D绘制。

https://www.youtube.com/watch?v=j-rCuN7uMR8

enter image description here

截至撰写本文时,我的“换色”脚本根本不起作用。我尝试使用它,因此当它获得一键点击时,它变为黄色。然后下一个单击为蓝色,下一个单击为黄色,依此类推。由于每个玩家只获得一键。

mm

我应该如何实施呢?任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:0)

在您的预制件上添加对撞机和刚体 然后在OnMouseDown中大写O并删除“ if(Input.GetMouseButtonDown(0)){” 当播放器单击您不想要的任何位置时,Input.GetMouseButtonDown(0)返回true

public Color[] colors; // allows input of material colors in a set sized array
    public SpriteRenderer rend;  // what are we rendering? the hex

    private int index = 1; //initialize at 1, otherwise you have to press the ball twice to change color


    // Use this for initialization
    void Start()
    {
        rend = GetComponent<SpriteRenderer>(); // gives functionality for the renderer
    }

    // Update is called once per frame
    void OnMouseDown()
    {
        // if there are no colors present nothing happens
        if (colors.Length == 0)
        {
            return;
        }


            index += 1; // when mouse is pressed down we increment up to the next index location

            // when it reaches the end of the colors it stars over
            if (index == colors.Length + 1)
            {
                index = 1;
            }

            print(index); // used for debugging
            rend.color = colors[index - 1]; // this sets the material color values inside the index

    } //onMouseDown

答案 1 :(得分:0)

首先,您需要适当大写OnMouseDown()才能调用它。

此后,由于使用的是SpriteRenderer,因此需要添加对撞机来检测鼠标单击事件。如OnMouseDown()文档中所述:

  

此事件发送到Collider或GUIElement的所有脚本。

由于两者都不存在,因此在预制件上单击添加组件> Polygon Collider 2D ,它将自动为您的精灵创建合适的几何形状(假设十六进制以外的所有内容都是透明的)。 / p>

最后,删除对Input.GetMouseButtonDown(0)的支票。 OnMouseDown已经捕获了单击鼠标的事实,并且运行OnMouseDown()的特定实例就是被单击的实例。