- Home /
How can i set the parent of an instantiated object like a weapon to my players hand.
My Inventory Script(Question is Under script) using UnityEngine; using System.Collections; using System.Collections.Generic;
public class Inventory : MonoBehaviour {
public int slotsX = 5;
public int slotsY = 5;
public GUISkin skin;
public List<Item> inventory = new List<Item>();
public bool showInventory = false;
public bool showCrafting = false;
public static List<Recipe> recipes = new List<Recipe> ();
public Transform Hand;
public Transform Axeprefab;
public GameObject WoodEquip;
private Item swappedItem;
private bool draggingItem = false;
private Item draggedItem;
private int prevIndex;
private int spikeCount;
private Rect invRect = new Rect(200, 140, 350, 420);
private Rect imageRect = new Rect(0, 0, 50, 50);
private Rect craftRect = new Rect(0, 40, 350, 350);
private Vector2 scrollPosition = Vector2.zero;
// Use this for initialization
void Start ()
{
Screen.showCursor = false;
invRect = new Rect(Screen.width / 2 - (invRect.width / 2), 0, invRect.width, invRect.height);
craftRect = new Rect(Screen.width / 2 - craftRect.width - invRect.width / 2, 0, craftRect.width, craftRect.height);
for(int i = 0; i < (slotsX * slotsY); i++)
{
inventory.Add(new Item());
}
new RecipeCreator();
}
// Update is called once per frame
void Update () {
if(Input.GetKeyDown(KeyCode.I))
{
showInventory = !showInventory;
showCrafting = !showCrafting;
Screen.showCursor = !Screen.showCursor;
if(draggingItem)
{
inventory[prevIndex] = draggedItem;
draggingItem = false;
draggedItem = null;
}
}
//Cheat Keys
if(Input.GetKeyDown("1"))
{
AddItem("Wood");
}
if(Input.GetKeyDown("2"))
{
AddItem("WoodPlanks");
}
if(Input.GetKeyDown("3"))
{
AddItem("Stone");
}
}
void OnGUI()
{
GUI.skin = skin;
if(showInventory)
{
GetCraftable();
invRect = GUI.Window(0, invRect, DrawInventory, "");
if(Event.current.type == EventType.mouseUp && draggingItem)
{
if(invRect.Contains(Event.current.mousePosition))
{
inventory[prevIndex] = draggedItem;
draggingItem = false;
draggedItem = null;
} else {
RemoveItem(prevIndex);
draggingItem = false;
draggedItem = null;
}
}
if(draggingItem)
{
CreateDraggedItem();
}
if(showCrafting)
{
craftRect = GUI.Window(5, craftRect, DrawCraftView, "");
}
}
}
void AddSpikes (float winX)
{
spikeCount = (int)Mathf.Floor (winX - 152) / 22;
GUILayout.BeginHorizontal ();
GUILayout.Label ("", "SpikeLeft");//-------------------------------- custom
for (int i = 0; i < spikeCount; i++) {
GUILayout.Label ("", "SpikeMid");//-------------------------------- custom
}
GUILayout.Label ("", "SpikeRight");//-------------------------------- custom
GUILayout.EndHorizontal ();
}
void DrawInventory(int windowId)
{
AddSpikes(windowId);
GUILayout.Label ("Inventory");
Event e = Event.current;
int i = 0;
for(int x = 0; x < slotsX; x++)
{
GUILayout.BeginHorizontal();
for(int y = 0; y < slotsY; y++)
{
GUILayout.BeginVertical();
GUILayout.Box (inventory[i].itemIcon);
if(inventory[i].multiItems)
{
if(inventory[i].itemCounter > 1)
{
GUI.Box(GUILayoutUtility.GetLastRect(), inventory[i].itemCounter.ToString(), "ItemCounter");
}
}
if(inventory[i].itemName != null)
{
if(IsMouseOver())
{
if(e.button == 0 && e.type == EventType.mouseDown && !draggingItem)
{
draggingItem = true;
prevIndex = i;
draggedItem = inventory[i];
inventory[i] = new Item();
}
if(Input.GetKeyDown(KeyCode.H))
{
Instantiate(Resources.Load("" + inventory[i].itemName), Hand.position, Hand.rotation);
}
if(e.type == EventType.mouseUp && draggingItem)
{
inventory[prevIndex] = inventory[i];
inventory[i] = draggedItem;
draggingItem = false;
draggedItem = null;
}
}
}
else {
if(IsMouseOver())
{
if(e.type == EventType.mouseUp && draggingItem)
{
inventory[i] = draggedItem;
draggingItem = false;
draggedItem = null;
}
}
}
GUILayout.EndVertical();
i++;
}
GUILayout.EndHorizontal();
}
GUI.DragWindow (new Rect(0, 0, 10000, 75));
}
void DrawCraftView(int windowID)
{
AddSpikes(craftRect.width);
Event e = Event.current;
GUILayout.Space(8);
GUILayout.Label("Crafting");
GUILayout.Label("", "Divider");
scrollPosition = GUILayout.BeginScrollView(scrollPosition);
for(int i = 0; i < GetCraftable().Count; i++)
{
if(GUILayout.Button(GetCraftable()[i]))
{
Craft(GetCraftable()[i]);
}
}
GUILayout.EndScrollView();
GUILayout.Label("", "Divider");
GUILayout.Space(8);
GUI.DragWindow(new Rect(0, 0, 10000, 75));
}
bool IsMouseOver()
{
return GUILayoutUtility.GetLastRect ().Contains (Event.current.mousePosition);
}
void CreateDraggedItem()
{
Rect tempRect = new Rect (Event.current.mousePosition.x + 5, Event.current.mousePosition.y, 64, 64);
imageRect = GUI.Window (2, tempRect, DrawDraggedItem, "", "DragImage");
}
void DrawDraggedItem(int windowID)
{
GUILayout.Box (draggedItem.itemIcon, "DragImage");
}
public void AddItem(int id)
{
if(Database.isItemMultiple(id))
{
if(InventoryContains(id))
{
AddItemToExisting(id);
return;
}
}
for(int i = 0 ; i < inventory.Count; i++)
{
if(inventory[i].itemName == null)
{
for(int j = 0; j < Database.items.Count; j++)
{
if(Database.items[j].itemID == id)
{
Database.CopyItem(inventory[i], Database.items[j]);
}
}
break;
}
}
}
public void AddItem(string name)
{
if(Database.isItemMultiple(name))
{
if(InventoryContains(name))
{
AddItemToExisting(name);
return;
}
}
for(int i = 0 ; i < inventory.Count; i++)
{
if(inventory[i].itemName == null)
{
for(int j = 0; j < Database.items.Count; j++)
{
if(Database.items[j].itemName == name)
{
Database.CopyItem(inventory[i], Database.items[j]);
}
}
break;
}
}
}
public void AddItem(Item item)
{
if(Database.isItemMultiple(item.itemID))
{
if(InventoryContains(item.itemID))
{
AddItemToExisting(item.itemID);
return;
}
}
for(int i = 0 ; i < inventory.Count; i++)
{
if(inventory[i].itemName == null)
{
inventory[i] = item;
break;
}
}
}
void RemoveItem(string name, int amount)
{
int removed = 0;
for(int i = 0; i < inventory.Count; i++)
{
if(inventory[i].itemName == name)
{
if(inventory[i].multiItems)
{
if(inventory[i].itemCounter > (amount - removed))
{
inventory[i].itemCounter -= (amount - removed);
break;
}
else if(inventory[i].itemCounter == (amount - removed)){
inventory[i] = new Item();
break;
} else {
removed += inventory[i].itemCounter;
inventory[i] = new Item();
if(removed >= amount)
{
break;
}
}
} else {
if(removed < amount)
{
removed ++;
inventory[i] = new Item();
} else {
break;
}
}
}
}
}
void RemoveItem(int index)
{
inventory[index] = new Item ();
}
bool InventoryContains(int id)
{
for(int i = 0; i < inventory.Count; i++)
{
if(inventory[i].itemID == id)
{
return true;
}
}
return false;
}
bool InventoryContains(string name)
{
for (int i = 0; i < inventory.Count; i++)
{
if (inventory [i].itemName == name)
{
return true;
}
}
return false;
}
bool InventoryContains(string name, int amount)
{
for (int i = 0; i < inventory.Count; i++)
{
if(inventory [i].itemName == name)
{
if (inventory [i].multiItems)
{
if (inventory [i].itemCounter >= amount)
{
return true;
}
} else {
return false;
}
}
}
return false;
}
void AddItemToExisting(int id)
{
for(int i = 0; i < inventory.Count; i++)
{
if(inventory[i].itemID == id)
{
inventory[i].itemCounter ++;
}
}
}
void AddItemToExisting(string name)
{
for(int i = 0; i < inventory.Count; i++)
{
if(inventory[i].itemName == name)
{
inventory[i].itemCounter ++;
}
}
}
public List<string> GetCraftable()
{
List<string> craftable = new List<string>();
for(int i = 0; i < recipes.Count; i++)
{
foreach(var mat in recipes[i].items.Keys)
{
if(InventoryContains(mat, recipes[i].items[mat]))
{
craftable.Add(recipes[i].itemName);
}
}
}
return craftable;
}
public void Craft(string item)
{
List<string> craftable = GetCraftable();
for(int i = 0; i < recipes.Count; i++)
{
if(recipes[i].itemName == item)
{
foreach(var mat in recipes[i].items.Keys)
{
RemoveItem(mat, recipes[i].items[mat]);
}
}
}
AddItem(item);
}
}
The item spawns like i want it to but it doesn't move with the player, it just floats in mid-air. i know that you need to set the parent to the hand object but when i tried it wouldn't work.
if(Input.GetKeyDown(KeyCode.H)) { GameObject Clone = Instantiate(Resources.Load("" + inventory[i].itemName), Hand.position, Hand.rotation); Clone.transform.SetParent(Hand); } This is what i tried but when i did i got the error " Cannot implicitly convert type UnityEngine.Object' to
UnityEngine.GameObject'. An explicit conversion exists (are you missing a cast?)"
Answer by Stardog · Feb 19, 2015 at 08:49 AM
Resources.Load just gives you an Object, so you have to convert it to a GameObject.
if(Input.GetKeyDown(KeyCode.H))
{
GameObject instance = (GameObject)Instantiate(Resources.Load("" + inventory[i].itemName), Hand.position, Hand.rotation);
instance.transform.SetParent(Hand);
}
Or try one of these:
GameObject instance = Instantiate(Resources.Load("" + inventory[i].itemName), Hand.position, Hand.rotation) as GameObject;
GameObject instance = Instantiate(Resources.Load<GameObject>("" + inventory[i].itemName), Hand.position, Hand.rotation);
GameObject instance = Instantiate(Resources.Load("" + inventory[i].itemName, typeof(GameObject)), Hand.position, Hand.rotation) as GameObject;
GameObject instance = Instantiate(Resources.Load("" + inventory[i].itemName, typeof(GameObject)), Hand.position, Hand.rotation);
Answer by Cherno · Feb 19, 2015 at 03:34 AM
Making a transform a child of another transform goes like this:
Transform childTransform;
Transform parentTransform;
childTransform.parent = parentTransform;
//For GameObjects:
GameObject childObject;
GameObject parentObject;
childObject.transform.parent = parentObject.transform;
how would I set the object I just instantiated as the childobject? i understand that the parent object needs to be the hand which I've set to a empty gameobject in the players hand and the child needs to be the instantiated item. but i don't know how to do the second part.
Just to add a bit more detail to the explanation... At the beginning of your script, set a public Transform parent
. Then (assu$$anonymous$$g your "hand" has a bone), make an Empty GameObject a child of that bone. Position the offset of the Empty appropriately. Then drag the Empty into the slot for the "parent" on the script.
There's also no reason for the //For GameObjects:
Setting a parent will always use the Transform anyway so just make the variable a Transform from the get-go.
Ive already done that. thats what the Transform hand is for. the item spawns in the empty but i just dont know how to set the instantiated items parent as the empty. i kind of have an idea how to do it when its not instantiated and when its a specific object. but for this it detects what the name of the item is and instantiates that item. im sorry if you're having trouble understanding. im trying my best to explain it but im kinda bad at that.