Search Unity

Apply force each time objects become active?

Discussion in 'Scripting' started by CoolCosmos, Jan 9, 2021.

  1. CoolCosmos

    CoolCosmos

    Joined:
    Nov 21, 2016
    Posts:
    247
    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?
     
  2. CoolCosmos

    CoolCosmos

    Joined:
    Nov 21, 2016
    Posts:
    247
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class FireMove : MonoBehaviour
    4. {
    5.     ObjectPooler objectPooler;
    6.  
    7.     Rigidbody rb;
    8.     GameObject impactObj;
    9.     Vector3 fireDirection;
    10.     [SerializeField] float fireThrust;
    11.  
    12.     void Awake()
    13.     {
    14.         rb = GetComponent<Rigidbody>();
    15.  
    16.         objectPooler = ObjectPooler.Instance;
    17.     }
    18.  
    19.     void OnCollisionEnter(Collision collision)
    20.     {
    21.         if (collision.gameObject.tag == "wall")
    22.         {
    23.             gameObject.SetActive(false);
    24.         }
    25.     }
    26.  
    27.     void OnEnable()
    28.     {
    29.         rb.velocity = -transform.forward * fireThrust;
    30.     }
    31. }
    32.  
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,742
    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:

    https://docs.unity3d.com/Manual/ExecutionOrder.html

    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.
     
    CoolCosmos likes this.
  4. CoolCosmos

    CoolCosmos

    Joined:
    Nov 21, 2016
    Posts:
    247
    Sorry for confusion. I just noticed that i didn't assign the objects "wall" tag. My bad...