Rigidbody 2D doesn't stop

384 views Asked by At

In my scene I am instantiating at runtime a prefab, which has a dynamic Rigidbody2D and a BoxCollider2D; It also has a script with an OnTriggerEnter2D method, that runs the following function:

/* ... */
public Rigidbody2D rigidbody;

private void StopMovement()
{
    rigidbody = GetComponent<Rigidbody2D>();
    rigidbody.velocity = Vector2.zero;
    Debug.Log(rigidbody.velocity);
}

Basically I want the object to stop when he collides with the trigger. The problem is it doesn't stop, and even if the console message says (0.0, 0.0) the rigidbody's inspector looks like this:

enter image description here

And as you can see, its velocity isn't actually zero. I tried adding

rigidbody.constraints = RigidbodyConstraints2D.FreezeAll;

but all it does is freezing the position on the prefab, not on the actual gameObject instance. And I don't get how that's possible, also considering that the Rigidbody field on the script is occupied by Ball(clone), which is the name of the gameObject that's in the scene. I also tried using GetComponent in Awake/Start instead of there, but the result was the same.

I've already looked up a bunch of other posts, both here and on UnityAnswers, but none of them could help me. What is happening exactly?

2

There are 2 answers

0
NicknEma On BEST ANSWER

Turns out that what caused that strange behaviour was related to a custom Event System, that's why it has taken so long to figure out. Basically I was assigning the prefab as the target object in the Event Listener's inspector, thinking that its effect would be automatically applied to all the instances of that prefab, but in the end it doesn't work like that. If anyone has the same issue, I solved it by putting the Event Listener component onto the vary target object, so basically it references itself and causes the expected behaviour.

enter image description here

Thanks for everyone's time, this can be closed now.

5
Leoverload On

You are accessing the prefab and not the actual gameObjecy and so the rigidbody. When you instantiate the ball use a

'GameObject ballClone = Instantiate(ballpref, pos, quaternion);'

In this way you can access to ballClone.getcomponent() and it will work fine