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. Dismiss Notice

Spawn a child at parent position C#

Discussion in 'Scripting' started by TD10074405, Sep 5, 2014.

  1. TD10074405

    TD10074405

    Joined:
    Aug 23, 2014
    Posts:
    35
    I have been writing a small adventure game which uses an inventory system to hold and use items collected around the game-world.

    Because my Karma is low on the Answers section, many of my threads simply fall into the abyss of the internet. SO.. I have come here, placing my faith in your hands that this (relatively simple) problem can be fixed.

    I am instantiating an item from OnGUI() which then spawns the item (supposed to be to the "Hand" of my player.) however at the current time it is spawning to a set location because I can't figure out how to make an instantiated item a child of another item.

    Here is a snippet of my code:

    <Code removed />

    EDIT: I now have items being spawned at parental object however there are two spawns per item, i,e in my hierarchy it will say "1911A1", "1911A1" under Hand.

    The second issue is that my items are being spawned around -700 below my objects position.

    The third is that some of my spawned items for the map are falling through the map but others of exact same object will not.. Hmnnn
     
    Last edited: Sep 5, 2014
  2. OboShape

    OboShape

    Joined:
    Feb 17, 2014
    Posts:
    836
    Afternoon,

    let me know if I'm reading this right.

    is the hand an object created on GUI, or are you positioning things in world space based on items drawn with GUITexture?

    if your spawning positions are out, are you converting between screen space co-ordinates and world space co-ordinates and vice versa.

    the last bit, if things that are on the scene dont fall through the map but instantiated items do, have you updated the prefab to have the same components and properties as the items that dont fall through.

    just a few thoughs off the top of my head to get the ball rolling :)
     
  3. TD10074405

    TD10074405

    Joined:
    Aug 23, 2014
    Posts:
    35
    Decided to split these issues with spoilers, bare with me lol

    The "Hand" is a tagged item on my player, it is an object that is an empty parent object (Where weapons are supposed to spawn)

    The OnGUI() function is being used for my Inventory, when you highlight an object in my inventory, hit the right mouse button it is spawning the item from the inventory to the game world as a child of the "Hand" object, which is good and what is supposed to happen! ✓

    The thing that's not supposed to happen is the item spawning at -700.00 (Units? Miles? KM? Px? Floats? whatever the unit is in the Transform in the inspector.) below that of the character and the hand (FPS style gaming) when it is called from the Inventory.

    The second thing is to do with ALL instantiated items, there are no issues with static objects, if the item is instantiated above a static (placed via the inspector) item and it drops onto the item, the instantiated object seems to become "Solid", the same is the case if two instantiated objects collide before they touch the floor/terrain, both seem to become solid and will then hit the floor and bounce/roll away whereas if the item is instantiated and then it doesn't touch anything before it hits the floor it will 3/4 times just plummet right through the terrain.

    The only difference I have found is when I created a map in World Machine, exported the RAW data, imported onto my terrain making it shaped a lot different. with more definition and height to the map, however this could be irrelevant as I only tested it once or twice so might have been a fluke!

    PS: I'm friends with a couple of guys from from LMZF ;)
     
  4. OboShape

    OboShape

    Joined:
    Feb 17, 2014
    Posts:
    836
    hehe yeah good bunch of old farts over there :) me being an afore said old fart too lol

    ill be on with a few of them thenight, bit of BF4 me thinks ;)

    right, the first one. ive created a small scene, and drawn a lifelike model and perfect sword :( ahem.

    so your player has a hand object and im assuming its position is located at the end of the arm.
    so when you click the hand object in the heirarchy you can see its gizmo at the end of the arm, like this.



    ok, ive then got a sword as a prefab.

    i created an empty gameobject, and put that inside the hand object above then reset its position, as that will make its 0,0,0 the centre of the hand., so i know that now the centre of the sword gameobject is at the centre of the hand. then i stuck in a blade and a hilt into the sword object, then moved it so that it looked in the right position.

    sword container in position

    then put a couple of scaled cubes in that to look like a sword :) ish


    then i made the sword (ie the parent of the cubes) a prefab and deleted it from the scene.


    so now i know that if i instantiate the sword at the hand it will be at the place i need it to be.

    heres the code that i used to test;

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class SpawnSword : MonoBehaviour {
    5.  
    6.     public GameObject mySword;
    7.     public Transform myLeftHand;
    8.  
    9.  
    10.     void Update ()
    11.     {
    12.        if (Input.GetKey(KeyCode.S))
    13.         {
    14.             Instantiate(mySword, myLeftHand.position, Quaternion.identity);
    15.         }
    16.     }
    17. }
    18.  

    fingers crossed you can get something from that, if not ill have to rethink what you could be doing.

    ill have a think about the next one too :)
     
    TD10074405 likes this.
  5. TD10074405

    TD10074405

    Joined:
    Aug 23, 2014
    Posts:
    35

    I thought I had solved it with a combination of both your solution and my own but it has not. I believe the issue is to do with the way I am spawning the objects. Because I am calling them from within the OnGUI() class rather than the Update() function they seem to drop down to the ground even using the spawn point "myHand" as a transform

    Calling them from the OnGUI() does create only one item, but it will simply fall to the ground - EDIT: I did a little bit of jigging a second ago and they will now spawn one item at the hand, however they are not parented to the object "Hand" nor are they "floating" with the hand and are just dropping to the floor, Some source:
    Code (CSharp):
    1.                         if(Backpack[ITM].Item.ITM_Icon != null){                     //It's got something in it!
    2.                             if(Input.GetMouseButtonDown(1)){                        //If we're Right-clicking on it, we can do some stuff with it.
    3.                                                                                     //Lets check out the items type
    4.                                 if(Backpack[ITM].Item.ITM_Type == INV_DEF.Item_type.Consumable && Stats.Health < Stats.MaxHealth){ //Item's a consumable, Food/Drink for health mainly.
    5.                                     Stats.AddHealth(5);                                //Add some health for the item, This is currently a set value.
    6.                                     Backpack[ITM].Item = new INV_DEF ();            //Remove our item from the inventory so we don't add it twice
    7.                                 }else if(Backpack[ITM].Item.ITM_Type == INV_DEF.Item_type.Weapon){ //If the item is a Weapon, we can equip it
    8.                                     if(Backpack[ITM].Item.ITM_Name == "Axe (Medievil)")
    9.                                         WEP_ID = 0;
    10.                                     if(Backpack[ITM].Item.ITM_Name == "Revolver (.38)")
    11.                                         WEP_ID = 1;
    12.                                     if(Backpack[ITM].Item.ITM_Name == "Wooden Plank (2X4)")
    13.                                         WEP_ID = 2;
    14.                                     if(Backpack[ITM].Item.ITM_Name == "Crowbar")
    15.                                         WEP_ID = 3;
    16.  
    17.                                     Instantiate(possItems[WEP_ID], GameObject.FindGameObjectWithTag("Hand").transform.position, Quaternion.identity);
    18.                                     Equipped = Backpack[ITM].Item;                    //Add the item to our clipboard
    19.                                     Backpack[ITM].Item = new INV_DEF ();            //Clear our backpack slot
    20.                                 }
    21.                             }                                          
    22.                         }else if(Backpack[ITM].Slot.Contains(MousePos)){
    23.                             if(Backpack[ITM].Item.ITM_Icon == null){
    24.                                 if(Input.GetMouseButtonDown(1)){
    25.                                     Debug.Log("Empty");
    26.                                 }
    27.                             }
    28.                         }
    If I call the item from the update function this happens Untitled-2.png

    Basically the items will spawn at the position of the had and then drop to the floor (Maybe because of rigidbody?) but then but it will then continue to spawn from the hand much water from a fountain. which could possibly come in handy for my environment!

    Hmn!! This is the last real thing holding the progress of my game up! Because I have managed to fix the issue of items falling through the map!
     
  6. OboShape

    OboShape

    Joined:
    Feb 17, 2014
    Posts:
    836
    when your instantiating your objects, have a stab at this t create them as children by setting their parent.

    ok so at the top ive got a couple of objects declared, so drag your prefab and what object you want to set the parent as.

    Code (CSharp):
    1.  
    2. public GameObject  thingToInstantiate;
    3. public Transform parentObject;
    4.  

    setting the parent can be done via the transform component, so the 'parentObject' ive just set to a Transform type, saves a wee bit of typing.

    Code (CSharp):
    1.  
    2. void Start()
    3.     {
    4.         GameObject NewClonedObject = (GameObject)Instantiate(thingToInstantiate,parentObject.transform.position,transform.rotation);
    5.         NewClonedObject.transform.parent = parentObject;
    6.     }
    7.  

    so that will instantiate a new object and set as a child, by telling it what its parent is :)

    hope that helps.


    Oh one more thingee, noticed that you are doing a find game objects with tag, is there no way you can do this once for the player and have it set so its not searching the whole scene each time you instantiate something,
     
    Last edited: Sep 7, 2014
  7. TD10074405

    TD10074405

    Joined:
    Aug 23, 2014
    Posts:
    35
    Find with tag was there for a random piece we were testing.

    Using the above script has worked, however I've had to remove Rigidbodies to make the item float at the hand, otherwise the items still drop to the floor but are now carried (dragged) around by the character Which isn't too much of a problem, I just created two prefabs:
    • Environmental: Spawns with a rigidbody for collection, destructed when picked up
    • Player: Spawns with item definition i.e type, name etc and has no rigid body
    which happens to be working for me!

    Thanks for all your help obo!
     
    OboShape likes this.
  8. OboShape

    OboShape

    Joined:
    Feb 17, 2014
    Posts:
    836
    no worries, glad i could help a wee bit.
    good that u got it going, gimme a shout when u get it up on tinterweb for a wee shot ;)