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

Instantiated GameObjects - Only one function call?

Discussion in 'Scripting' started by macmouse, Feb 13, 2015.

  1. macmouse

    macmouse

    Joined:
    Jun 5, 2014
    Posts:
    37
    Hi,

    I have instantiated 5 game objects. The objects can destroy each other. When for example two objects collide, they are destroyed. Now I want to add an explosion on the point where they are destroyed. This is not the problem. I programmed it myself. It's working.

    All clones have this in the script:
    Code (CSharp):
    1.  void OnCollisionEnter2D(Collision2D coll) {
    2.         Destroy(gameObject);
    3.         InstantiateExplosion();
    4.     }
    And this is my problem. The clones are calling two times the InstantiateExplosion(); function. How can I call the function only once?

    Thanks in advance.
     
    Last edited: Feb 13, 2015
  2. Zaladur

    Zaladur

    Joined:
    Oct 20, 2012
    Posts:
    392
    You could put this line in there:

    Code (csharp):
    1. if(GetInstanceID() > other.gameObject.GetInstanceID()) InstantiateExplostion();
    I don't know if that is the best permanent solution, but it should guarantee that when both objects collide, only one of them triggers an explosion.

    This could be a problem, for example, if you want the objects to be destroyed and trigger an explosion when they hit walls.
     
  3. macmouse

    macmouse

    Joined:
    Jun 5, 2014
    Posts:
    37
    Great. Simple Solution. Thank You.
     
  4. lordconstant

    lordconstant

    Joined:
    Jul 4, 2013
    Posts:
    389
    If you reorder the fuctions it will work. You are destroying the current object before it can call the second function.
     
  5. Zaladur

    Zaladur

    Joined:
    Oct 20, 2012
    Posts:
    392
    This doesn't solve anything. The instantiate calls are still going through for him - the destroy resolves at the end of the frame. His issue is that this script is attached to two different game objects and both are being called - he wants a portion of it only called on one script.

    I will agree that, for consistency and readability, destroy should go at the end, but it won't address the problem here.
     
  6. lordconstant

    lordconstant

    Joined:
    Jul 4, 2013
    Posts:
    389
    Ah sorry was on phone at the time and missed the bit at the bottom.