- Home /
Trying to create a script that changes an objects material when collision occurs, help? C#
I have an object that will be the subject of collision damage when impacted by another object in a game. Depending on the force of impact I want to change the material color of the object, softer impact being green, medium = yellow, hard = red and critical being black. I am a total novice and pulling at straws to get this to work. Using C#
Answer by Matt1000 · Mar 17, 2017 at 09:31 AM
That's pretty easy. It is as simple as having OnCollisionEnter (Collider other)
method. This method is called on every just-made collision. The you'll need a variable which saves your force/speed. To do this you just need to save your previous position and substract it the new one. Then at the moment of collision you should check for their numbers. E.g:
public void OnCollisionEnter (Collider other) {
if (speed.x < 3)
color = green;
else if (speed.x < 6)
color = yellow;
else if (speed < 9)
color = red;
else
color = black;
}
}
This is only for one direction though. But you can simply make it. Hope it helps :)