- Home /
pick up a gun problem
Hey everyone, I have a problem with my script and I don't know how to resolve it. I am new to unity and I may have done a huge mistake that can be very obvious to someone so please help me. Here's the code:
using UnityEngine;
using System.Collections;
public class GunPuckUp : MonoBehaviour {
public Transform SpawnTo;
private RaycastHit hit;
public Ray ray;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(Input.GetKeyUp(KeyCode.E)){
Vector3 fwd = transform.TransformDirection(Vector3.forward);
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, hit) && hit.transform.tag == "Gun"){
hit.transform.parent = SpawnTo;
hit.transform.position = SpawnTo.transform.position;
hit.transform.rotation = SpawnTo.transform.rotation;
}
}
}
}
Answer by pixelmixer · Oct 23, 2012 at 06:23 PM
Assuming your gun (SpawnTo) already exists in the scene, then you'll just need to reposition it to where you need it to show up after it gets parented (also assuming that the parenting happens successfully to begin with).
You can set SpawnTo's localPosition to move it to the center of the parent like so:
Transform gun = hit.transform;
gun.parent = SpawnTo;
gun.localPosition = Vector3.zero;
If SpawnTo is actually a prefab that is not in the scene, then you need to make sure its being instantiated first. Something like this might send you on the right direction.
Transform gun = Instantiate(GUNPREFAB, Vector3.zero, Quaternion.identity) as Transform;
gun.parent = SpawnTo;
gun.localPosition = Vector3.zero
It would help to have a little more information about what exactly isn't working, if its not actually getting reparented then there may be an issue with the Raycast or your "Gun" tag, though that looks ok at a glance - just verify that the gun GameObject is actually tagged "Gun" in the editor.
The SpawnTo is an object in the game attached to the player. Sorry for not specifying what the problem is I corrected the script to how I intended it to be but unity says that there is a problem about the 2nd argument in the Physics.Raycast.
Ahh ok. The 2nd argument should be an "out". Eg: Physics.Raycast(ray, out hit)
You may also need to split up this IF statement.
if(Physics.Raycast(ray, out hit) && hit.transform.tag == "Gun"){
You could make it something like
if(Physics.Raycast(ray, out hit)){
if( hit.transform.tag == "Gun" ){ hit.transform.parent = SpawnTo; hit.transform.position = SpawnTo.transform.position; hit.transform.rotation = SpawnTo.transform.rotation;
} }
I corrected it and now it doesn't show me any error but when I start the game it doesn't do anything when I press E and I checked and the gun is tagged as "Gun".
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Script suddenly stopped working properly 1 Answer
switching gun on screen with gun you pick up. 3 Answers
Weird problem with gunscript 2 Answers