- Home /
Parent an object to the camera via script?
I have a script so far and I want it to send a raycast out to an object and then attach that object to the main camera - like in Skyrim and Portal etc. I know I will have to do something else to make it have a rigid body but for now I want it to parent it to the camera as long as the E key is pressed and then un-parent it when it is let go. My script so far:
#pragma strict
function Update ()
{
if (Input.GetKey ("e"))
{
var ray : Ray = Camera.main.ViewportPointToRay (Vector3(0.5, 0.5, 0));
var hit : RaycastHit;
if (Physics.Raycast (ray, hit))
{
//hit.transform.SendMessage ("PickUp", SendMessageOptions.DontRequireReceiver);
}
}
}
I put // in there to show that that's how I think it may work but if you know a better way then you can say. So, how can I go about doing this. I guess somehow make the raycast send a message to the object it hits and then the object will run a function where it attaches itself to the camera?
Answer by gfoot · Jan 28, 2014 at 10:13 PM
You can send a message, or call a method, or simply perform the parenting yourself directly.
If you want to call a method I'd recommend applying a custom component to any objects which may be picked up, which handles the request. Then inside your 'if' statement you can do something like this to check the hit object is able to be picked up, and if so, tell it to do so:
CarriableObject carriable = hit.GetComponent<CarriableObject>();
if (carriable != null)
{
carriable.BeCarried();
}
Any animation required can be applied by CarriableObject to the object itself, e.g. smoothly moving it into the carrying position.
You'd probably need to also record which object was being carried, so that you can detect when the E key is released and tell the object to stop being carried.
Your answer
Follow this Question
Related Questions
Children don't move with parent 1 Answer
How to make an object the child of another object through code? 1 Answer
Checking Child collisions through parents 1 Answer
Problem with prefab parent and children objects that need to be instantiated multiple times. 1 Answer
Trouble assigning transforms of two raycast hits to two different objects. 1 Answer