Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Easy coding

Discussion in 'Scripting' started by Corva-Nocta, Feb 16, 2018.

  1. Corva-Nocta

    Corva-Nocta

    Joined:
    Feb 7, 2013
    Posts:
    801
    I'm working on a multiplayer game (though this problem isn't about multiplayer) which is the reason I have to do this the way it has to be done. I am having trouble with destroying game objects and need help referencing a script on an empty game object that will do the destroying (multiplayer is weird) sadly, simply putting Destroy(gameObject) on the object to be destroyed does not work in multiplayer the way it works in single player.

    I have a script on my player:
    Code (csharp):
    1. public Interactable focus;
    This is what runs a lot of the scripts I have, mostly for interacting and combat. This is the information I want to send to my empty game object, but I'm not exactly sure how.

    On my empty game object I have only 1 function:
    Code (csharp):
    1. public void NetworkDestroy ()
    2. {
    3.    Destroy (gameObject);
    4. }
    I understand that you can search for gameobjects by their tag, but I want to avoid this methode because I need the tag for other things. How else can I reference it?

    So I need to somehow send the data into that script. I know this can be done, I have just been up doing too much coding (which I am not good at) and my brain is fried.

    Any help at all would be great!
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,186
    Is that method suppose to destroy it's own gameObject or destroy a different gameObject? Just for clarity.

    If you are destroying other gameObjects, make it a static method and pass in the gameObject

    Code (CSharp):
    1.     public static void DestroyInstance(GameObject go)
    2.     {
    3.         Destroy(go);
    4.     }
     
  3. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    If you're using UNet, they have attributes that may be helpful for you.
     
  4. Chris-Trueman

    Chris-Trueman

    Joined:
    Oct 10, 2014
    Posts:
    1,260
    One other caveat when dealing with multiplayer. Only the server can destroy objects across the network, with NetworkServer.Destroy(GameObject). Using destroy on a client and not the host will only destroy it for that client, and then that client will start getting errors when the server sends messages for that object.

    So if you are doing it from a client you need to use a Command that will call NetworkServer.Destroy which will update all the clients connected.