【问题标题】:Change the color of an instantiated prefab Unity更改实例化预制 Unity 的颜色
【发布时间】:2019-11-19 18:19:19
【问题描述】:

所以玩家点击一个按钮来创建一个盒子。我需要这个盒子在几种颜色之间随机变化。我还需要这个盒子有一个与所述颜色相对应的标签。绿框 - “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】:
    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 的着色器属性,这是着色器中的默认颜色元素,您当然可以根据着色器设置更多。

    【讨论】:

    • 您好,谢谢您的回复。所以我将它切换到 material.SetColor 但它没有改变它。我是否正确获得了对实例化游戏对象渲染器的引用?如果这有什么不同的话,它就是一个预制件。
    • 哦,是的,这行不通。您正在实例化盒子,您需要为您实例化的盒子获取渲染器,因为它是新的。我将在答案中更新我的代码。
    • 所以现在没有错误但是这些框是不可见的!
    • 我假设您正在某处设置boxColor 的值?根据上面的代码,它的默认值为 (0,0,0,0),因此是透明的
    • @Neilk boxrenderer 被用作局部变量,但在类级别声明。您应该从类中删除声明并将其保留在本地。
    猜你喜欢
    • 1970-01-01
    • 2018-07-28
    • 1970-01-01
    • 2019-04-01
    • 2016-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-27
    相关资源
    最近更新 更多