【问题标题】:Change Material when collision than change color by color picker碰撞时更改材质而不是通过颜色选择器更改颜色
【发布时间】:2025-12-09 20:55:02
【问题描述】:

我有不同材质的不同物体,一个没有材质的盒子物体,现在我可以通过以下代码在抓取不同物体碰撞盒子时更改盒子材质

public class Target : MonoBehaviour{

公开材料 currentTargetMaterial;

void OnCollisionEnter(Collision collision)
{
    //Check for a match with the specific tag on any GameObject that collides with your GameObject
    if (collision.gameObject.tag == "Player")
    {
        //get the original mesrender 
        MeshRenderer mesRender = GetComponent<MeshRenderer>();
        //from original meshrender to get the original material
        Material oldMaterial = mesRender.material;
        //the gameobject who clooide with
        GameObject who = collision.gameObject;
        //get rhe collide object's meshrender
        MeshRenderer sourceRender = who.GetComponent<MeshRenderer>();
        //get the collider's object's material
        Material sourceMaterial = sourceRender.material;
        //change material
        mesRender.material = sourceMaterial;
        currentTargetMaterial = sourceMaterial;
        Debug.Log("NOW IS " + currentTargetMaterial);
    }

我有另一个类调用 Applycolor 来处理将颜色应用到框,我尝试使用

public Material currentTargetMaterial;

通过以下代码将材质传递给 Applycolor 类

public class Applycolor : MonoBehaviour
{
    public FlexibleColorPicker fcp;
    public Material material;
    Target targetObject = new Target();
   
   
    private void Update()
    {
       Material rightnow =  targetObject.nowMaterial();
       Debug.Log("current is " +  rightnow );
        material = rightnow;
        material.color = fcp.color;
    }

但我无法获得材料,我是初学者,请帮助:(

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    对不起,太笨了,我在 ApplyColor 类中添加了这些行,它已经解决了

    {
        public FlexibleColorPicker fcp;
        public Material material;
        GameObject box;
        Material boxMaterial;
        
    private void Update()
    {
        box = GameObject.Find("targetBox");
        boxMaterial = box.GetComponent<Renderer>().material;
        material = boxMaterial;
        material.color = fcp.color;
    } 
    

    【讨论】:

      最近更新 更多