When the rigidbody falls and hits the ground in the start of the game it performs the code, but after ~2 times of doing the explosion when touching the ground at a certain speed it won’t work anymore regardless how fast it hits the ground / how many times it hits the ground…
Here’s the script:
using UnityEngine;
public class Red : MonoBehaviour
{
private float radius = 20.0f;
private float power = 200.0f;
public GameObject explosionEffect;
private Rigidbody RigidBody;
private void Start()
{
RigidBody = GetComponent<Rigidbody>();
}
private void OnCollisionEnter()
{
//if "red" hits an object at this speed..
if (RigidBody.velocity.magnitude >= 5)
{
//"red" explodes..
GameObject explosionInstance = Instantiate(explosionEffect, transform.position, transform.rotation);
//affecting other rigidbodies..
Collider[] colliders = Physics.OverlapSphere(transform.position, radius);
foreach (Collider nearbyObject in colliders)
{
RigidBody = nearbyObject.GetComponent<Rigidbody>();
if (RigidBody != null)
{
//and adds a force.
RigidBody.AddExplosionForce(power, transform.position, radius);
}
}
Destroy(explosionInstance, 1); //destroys the particles game object.
}
}
}
When you say “On Collision detect stops working” I presume you’ve not debugged it and verified if it actually gets into the “OnCollisionEnter” but instead mean by this that your script just doesn’t do what you want?
Line 13 you set “RigidBody” to the body on this script which you use to check velocity magnitude. You’re saying it doesn’t even get here by saying “On Collision” doesn’t work. You then, for some unknown reason, reassign it to something completely different on line 28. This will leave it at some random body you added a force to so you end up checking its velocity magnitude.
You should, in the very least, debug this yourself by attaching a debugger and/or adding in a “Debug.Log()” statement to verify things. This is far quicker than writing forum posts and waiting for replies.
Alright you were right and the problem is in the if statement inside of the OnCollisionEnter method on line 19.
Now that I’ve found the problem I have no idea how to fix it, could you help me with this?
Yes but it should be obvious from what I said TBH; don’t assign that temporary Rigidbody you look for (Line 28) into the “RigidBody” field, place it in a different temporary one like “var nearbyBody = nearbyObject.GetComponent();” or something.