- Home /
How to load an item into the player's hand by clicking on a gameObject.
I need help with my inventory. My game is a third person game with a very simple inventory. For my inventory I want three boxes to be parented with the main camera so they stay on the same spot on the screen. Then when the player clicks on one of the boxes it loads an item into the players hand and when you click it again it gets rid of the item. This is the code I have.
var Shovel: Rigidbody;
var Spawn : Transform;
function OnMouseDown() {
var Shovel1= Instantiate (Shovel, gameObject.FindGameObjectWithTag("SpawnPoint").transform.parent.position, Quaternion.identity);
Shovel1.transform.parent = this.transform;
}
It works in that it loads the shovel where the players hand is but once I move the player the shovel stays where it was relative to the camera. But I want it to stay with the hand. Any help would be appreciated.
What is this script attached to? If it is attached to the camera the parent will be the camera, if it is attached to the hand the parent will be the hand.
If this script is on the camera and you want it to stay on the camera. Then do this:
Shovel1.transform.parent = GameObject.Find("HandObjectNameInHeirarchy");
When I use that code I get this error.
Assets/Code/InventoryChanger.js(14,59): BCE0022: Cannot convert 'UnityEngine.GameObject' to 'UnityEngine.Transform'.
You need to actually reference the transform.
Shovel1.transform.parent = GameObject.Find("HandObjectNameInHeirarchy").transform;
Thank You!!! It works now. How do I make your comment the answer?
Answer by Dax65 · Feb 25, 2014 at 04:47 PM
Thank you CodinRonin for your answer. It now works properly with this code for those who will have the same problem in the future.
var Shovel : Rigidbody;
var Spawn : Transform;
function OnMouseDown() {
var Shovel1= Instantiate (Shovel, gameObject.FindGameObjectWithTag("SpawnPoint").transform.parent.position, Quaternion.identity);
Shovel1.transform.parent = GameObject.Find("SpawnPoint").transform;
}
It's not ok to rewrite what people answer you youreself and mark it as you answered the question. I downvoted.
That is what I had to do because your answer was a comment not an answer. I did this so people can know what I did that fixed it to help people in the future who have the same problem.
Your answer
Follow this Question
Related Questions
Spawn inside of a parent 1 Answer
"Center On Children" programmatically 1 Answer
Trying to make a simple inventory: 0 Answers
Objects are destroyed/disfunctional after changing scene 3 Answers