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

Double Spawn

Discussion in 'Scripting' started by Greywolf6, Oct 19, 2021.

  1. Greywolf6

    Greywolf6

    Joined:
    Oct 20, 2020
    Posts:
    10
    I am using the below code to spawn a crashed item on collision. Sometimes, not always, I get a double spawn of the crashed vehicle. The player container is holding the normal vehicle.


    Code (CSharp):
    1. using System.Collections;
    2. using UnityEngine;
    3. using UnityEngine.SceneManagement;
    4.  
    5. public class CrashedSleigh : MonoBehaviour
    6. {
    7.     public GameObject crashedSleigh;
    8.     public GameObject playerContainer;
    9.  
    10.     void OnCollisionEnter(Collision collisioninfo)
    11.     {
    12.         if (collisioninfo.collider.tag == "Obstacle")
    13.         {
    14.             Instantiate(crashedSleigh, transform.position, transform.rotation);
    15.             Destroy(playerContainer);
    16.         }
    17.  
    18.        
    19.     }
    20. }
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,970
    I think you can hit more than one collider in a given frame... is that it?

    You can print out the name of the collider you hit at the start of the method... it is in
    collisioninfo
     
  3. Greywolf6

    Greywolf6

    Joined:
    Oct 20, 2020
    Posts:
    10
    I will try that. Its very random, I was playing last night testing something else and hit one of my trees with a single collider and it spawned three. It was quite amusing but not what Im looking for.
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,970
    And that's why we're all in gamedev.

    One other obvious thought is: doublecheck you didn't stick this in two places on your object, one that is on a collider that is harder to hit, that you didn't originally intend it to be. I find physics collisions are almost always explainable once you start printing out the names of who was involved.

    "Oh, I was hitting the monster's left toenail... no wonder I died..."