- Home /
Material array not working,
Hi. I am having trouble with a project I've been working on. I have an object and I need it to change materials when the player collides with it. I followed a tutorial and it originally worked perfectly, but it just stopped registering the material array in the inspector one day and I can't work out why. All the collisions and everything works it is literally just the array. Here is my code:
Material[] materials;
private Renderer rend;
void Start ()
{
rend = gameObject.GetComponent<Renderer>();
rend.enabled = true;
rend.sharedMaterial = materials[0];
}
private void OnCollisionEnter(Collision col)
{
if (col.gameObject.tag == "Player")
{
rend.sharedMaterial = materials[1];
}
}
Can you elaborate on what is not working? How are you assigning materials to the array?
Answer by Grocho · Jun 30, 2018 at 08:35 AM
The problem may be in a different script. See if something else is fiddling with the render or material.
Answer by brotar · Jul 03, 2018 at 06:34 AM
Changing material itself doesn't have an issue. Below code should work.
public Material[] materials;
private Renderer rend;
void Start()
{
rend = gameObject.GetComponent<Renderer>();
rend.enabled = true;
rend.sharedMaterial = materials[0];
}
private void OnCollisionEnter(Collision col)
{
Debug.Log(col.gameObject);
if (col.gameObject.tag == "Player")
{
rend.sharedMaterial = materials[1];
}
}
If the OnCollisionEnter function is not called, there are 2 reasons. First, the OnCollisionEnter function could not be called because of inappropriate collider&rigidbody setting. You can simply check it with Debug.Log() in OnCollisionEnter. About collision check this: https://docs.unity3d.com/Manual/CollidersOverview.html. Scroll down below and see collision action matrix. Second, It is not called if you disabled physics collision between layers or colliders. Go to Edit/Project Setting/Physics and check Layer Collision Matrix. Also, check if you are using Physics.IgnoreCollision or Physics.IgnoreLayerCollision. Hope this helps you.
I should probably say that after playing with my script for a while I managed to get all the collisions working; when the player and ground collide the ground turns a strange purple colour. The problem is that the array is not registered in the inspector so I have no way to choose the materials I want.
Your answer
Follow this Question
Related Questions
How can I get a variable from another player? 0 Answers
How to make Boolean not add more than one integer? 2 Answers
Destroy by Contact (OnTriggerEntry) - destroying more then i want. 0 Answers
Script won't execute on assigned 3d object but on simple cube 0 Answers
How to detect an object which be in FOV of certain camera ? 1 Answer