change color before and during collision
i want to change color of object before and during collision. no problem changing it using OnCollisionEnter when two of the colliders collide. any advice on how to also change the color before objects collide each other? is it that I need to update the collider.contact.offset ?
pls help. thx in advance.
Answer by TBruce · Sep 27, 2016 at 03:40 AM
Lets say you have a cube. Now add an empty game object to the cube so that your hierarchy looks like this
The Cube already has a BoxCollider on it. Start by copying the collider from the cube. You do this be selecting the little gear icon in the upper right corner of the BoxCollider and select Copy Component from the drop down menu.
Now go back to the empty game object that you created and select the little gear icon in the upper right corner of the transform and select Paste Component as New from the drop down menu.
Now go back to the cube and make that BoxCollider larger than the cube - make it large enough so it is at the point where you want the color to change before collision.
Note you need to check Is Trigger on all colliders (this will not work properly if not).
Now add this script to both the Cube and child object.
using UnityEngine;
using System.Collections;
public class ColoredCube : MonoBehaviour
{
public Color newColor = new Color(1.0f, 1.0f, 1.0f, 1.0f); // change this to desired color
public bool changeColor = true; // optional flag
public string objectToCollideWith = "Block"; // used to determine object fo collision
public Renderer renderer = null;
void OnTriggerEnter(Collider col)
{
if ((changeColor) && (col.transform.tag == objectToCollideWith) && (renderer != null))
{
renderer.material.color = newColor;
}
}
}
Set all variables for each script on the cube and child object in the inspector (drag and drop the cube to the renderer variable in both scripts).
On the separate object that will be colliding with the cube it needs a collider (with Is Trigger checked) and it needs a Rigidbody (with Use Gravity un-checked).
thx for prompt reply.
tried but no changes. no collision and color change.
I tried similar way which works for me. - GameObject collider to be bigger than cube size and is trigger. - cube collider to be same size as cube. non-trigger. - target object collider to be non-trigger. - all must be in same layer.
this method works for me. object collides and changes color.
thx for replying. appreciate your help.
Please take a look at this Unity package to see a working version in action.
Your answer
![](https://koobas.hobune.stream/wayback/20220612093538im_/https://answers.unity.com/themes/thub/images/avi.jpg)