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

How to detect a collision inside another method?

Discussion in 'Scripting' started by big_stoater, May 6, 2018.

  1. big_stoater

    big_stoater

    Joined:
    Jun 25, 2014
    Posts:
    13
    Hello!

    I'm quite new to Unity and C# and I cannot workout how to achieve the following:

    I have a method that detects when the player gets close to an object (fuel pickup), when the player fly's within a certain distance of the object the object moves up towards the player. If the object hits the player I want to detect the collision and destroy the object.

    As far as I know you cannot call onCollisionEnter from inside another method so i have no idea how to do this.

    Here's my fuel pickup code:

    Code (CSharp):
    1.  private void BarrelPickup()
    2.     {
    3.         if (Vector3.Distance(fuelBarrel.transform.position, this.gameObject.transform.position) < 10.0f)
    4.         {
    5.             fuelBarrel.GetComponent<Rigidbody>().useGravity = false;
    6.             fuelBarrel.transform.position = Vector3.MoveTowards(fuelBarrel.transform.position, this.gameObject.transform.position, 5 * Time.deltaTime);
    7.         }
    8.         else
    9.         {
    10.             fuelBarrel.GetComponent<Rigidbody>().useGravity = true;
    11.         }
    Thanks in advance!
     
  2. big_stoater

    big_stoater

    Joined:
    Jun 25, 2014
    Posts:
    13
    I got it sorted, I added a collision method elsewhere then did a null check at the start of the BarrelPickup method and it works as expected.
     
  3. -JoSeM-

    -JoSeM-

    Joined:
    Jul 8, 2014
    Posts:
    9
    I think you could put a sphere collider (trigger) on the fuel. Then, cast on yor player "onCollisionEnter", check if it is colliding with the fuel collider, then call inside onCollisionenter the BarrelPickup function