更改实例化的预制Unity的颜色

问题描述 投票:0回答:1

所以玩家点击按钮创建一个盒子。我需要此框在几种颜色之间随机变化。我还需要此框具有对应于所述颜色的标签。绿框-“ greenBlock”标签等。

我已实例化该框,然后尝试使用material.color更改其材质。它什么也没做。我看到了sharedMaterial的建议,但尝试过发现它最终只是改变了场景中每个游戏对象的颜色。我想我正在正确获取盒子预制渲染器?任何帮助,将不胜感激!

这是我到目前为止的内容:


public class ButtonScript : MonoBehaviour
{
    public GameObject Box;
    public Transform spawnpoint1;
    public Transform spawnpoint2;
    public Rigidbody2D player;
    public Renderer boxRenderer;

    [SerializeField]
    private Color boxColor;
    [SerializeField]
    private AudioSource actionSound;

    // Update is called once per frame
    private void Start()
    {
        //boxRenderer = Box.gameObject.GetComponent<Renderer>();
        boxRenderer = GameObject.Find("Box").GetComponent<Renderer>();  //  Find the renderer of the box prefab
    }


    public void OnTriggerStay2D(Collider2D col)
    {
        if (player) //  If it's the player in the collider trigger
        {
            if (Input.GetKeyDown(KeyCode.E))
            {
                Instantiate(Box, spawnpoint1.position, Quaternion.identity);
                boxRenderer.material.color = boxColor;  //  change the color after it is instantiated
                actionSound.Play();
            }
        }

    }

}

c# unity3d renderer
1个回答
0
投票
boxRenderer.material.SetColor("_Color", boxColor);

boxRenderer.material.color = new Color(0.5, 0.5, 0.0, 1.0);

并且当实例化该框时,由于它是一个新对象,因此此时需要获取该框的渲染。因此:

       if (Input.GetKeyDown(KeyCode.E))
        {
            Box = Instantiate(Box, spawnpoint1.position, Quaternion.identity);
            boxRenderer = Box.transform.GetComponent<Renderer>();
            boxRenderer.material.color = boxColor;  //  change the color after it is instantiated
            actionSound.Play();
        }

请注意,您已经创建了新颜色并进行了分配,您不能在此处修改颜色,因为它可能会在使用相同材质的其他对象上使用。

在文档中签出SetColor,即设置称为_Color的着色器属性,这是着色器中的默认颜色元素,当然,根据着色器,您可以拥有更多的属性。

© www.soinside.com 2019 - 2024. All rights reserved.