Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

rigidbody.AddForce not working

Discussion in 'Getting Started' started by ElectricMonkey, Apr 8, 2015.

  1. ElectricMonkey

    ElectricMonkey

    Joined:
    Mar 10, 2015
    Posts:
    12
    I'm trying to apply a knockback to the player after he is hit by the enemy. They're both rigidbodies so I thought it shouldn't be that hard. For debug purposes I've set it so it does it everytime they collide.

    Here's the code:


    void OnTriggerEnter (Collider other)
    {
    // If the entering collider is the player...
    if(other.gameObject == player)
    {
    this.rigidbody.AddForce(target.rigidbody.velocity * force);
    // ... the player is in range.
    playerInRange = true;

    }
    }

    Force is set to be a public int and is set to 200 atm in unity.

    Nothing happens. I'm sure the colliders are setup right because playerInRange gets set to true.

    What could be the problem?
     
  2. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    20,141
    Quick property accessors were removed. You have to use GetComponent now. The tutorials haven't been updated yet.

    Code (csharp):
    1. this.GetComponent<Rigidbody>().AddForce(target.GetComponent<Rigidbody>().velocity * force);
     
    BrandyStarbrite likes this.
  3. ElectricMonkey

    ElectricMonkey

    Joined:
    Mar 10, 2015
    Posts:
    12
    Thanks for the reply. I've got an older version of Unity so it's probably based on the old one?

    I've tried both and they still dont work unfortunately.
     
  4. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    20,141
    Both technically work on pre-5.0. I've just gotten so used to correcting that problem that I completely failed to realize it wasn't the problem you were having. :p