- Home /
How to make a gameobject share the material of the collider it collides with?
Hi,
I am looking to have the material of a game object changed to the material of the object that collides with it. I haven't scripted much before but am starting with this:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class ChangeMaterial : MonoBehaviour { public Material[] material; public Renderer rend; // Use this for initialization void Start () { rend = GetComponent(); rend.enabled = true; rend.sharedMaterial = material[0]; }
void OnCollisonEnter (Collision col)
{
if (col.gameObject.tag == "Box")
{
rend.sharedMaterial = material[1];
}
else
{
rend.sharedMaterial = material [2];
};
}
}
Does the shared material call mean that the material will be change to the one of the collider or one which has been assigned to it in the inspector? This script isn't working, and was wondering what the issue might be.
Thanks.
Answer by SkaredCreations · Sep 20, 2018 at 09:58 AM
You should change the array materials of the Renderer, instead of sharedMaterial.
Answer by KittenSnipes · Sep 20, 2018 at 10:22 AM
@rosie-chote If you do a little reading in the docs on Unity it will lead you in the right direction. I absolutely recommend following YouTube tutorials and the Unity tutorials when moving on further in development because if you continue to run in to problems now then wen it gets complicated you won’t be able to do anything.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ChangeMaterial : MonoBehaviour {
public Renderer rend;
// Use this for initialization
void Start ()
{
rend = GetComponent<Renderer>();
rend.enabled = true;
}
void OnCollisonEnter (Collision col)
{
if (col.gameObject.GetComponent<Renderer>() != null)
{
rend.material = col.gameObject.GetComponent<Renderer>().material;
}
}
}
Your answer
Follow this Question
Related Questions
What happens to the instantiated material after i change the .sharedMaterial? 1 Answer
How to check if two objects share the same material within an if statement? 0 Answers
Can't set sharedmaterials 1 Answer
How to set second material to a second submesh in a combined mesh? 0 Answers
How can you allow an object to collide with a stationary character controller? 1 Answer