Apply force each time objects become active?

Hi there,

I’m using object pooling to spawn objects on the scene. I apply force the projectiles on Start() when they become active then disable them when they collide with wall. But after first time, Start() method is not working when they become active again. I tried using OnEnable method and it didn’t work too.

How can i apply force once when objects become active?

using UnityEngine;

public class FireMove : MonoBehaviour
{
    ObjectPooler objectPooler;

    Rigidbody rb;
    GameObject impactObj;
    Vector3 fireDirection;
    [SerializeField] float fireThrust;

    void Awake()
    {
        rb = GetComponent<Rigidbody>();

        objectPooler = ObjectPooler.Instance;
    }

    void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.tag == "wall")
        {
            gameObject.SetActive(false);
        }
    }

    void OnEnable()
    {
        rb.velocity = -transform.forward * fireThrust;
    }
}

This should work, ASSUMING a) your object pooler is turning the object off, and b) the Rigidbody reference is still valid, and c) the Rigidbody has woken up.

That’s a lot to assume, so it might be better to just set a boolean flag such as fresh in the OnEnable(), then checking that in your FixedUpdate() and putting the force there, then clearing the fresh.

Here is some timing diagram help:

Otherwise, to help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run?
  • what are the values of the variables involved? Are they initialized?

Knowing this information will help you reason about the behavior you are seeing.

1 Like

Sorry for confusion. I just noticed that i didn’t assign the objects “wall” tag. My bad…