- Home /
The question is answered, right answer was accepted
Problem assigning transform variable to prefab.
I'm trying to have an object become parented to a character's bone when the character touches the object. I have to do it a bit differently than the typical method however, because my character is a prefab that is created when the scene starts. Therefore, I can't simply drag and drop the object in Unity to get it's transform. Instead I am trying to assign the transform in script, but the examples that I have found for this don't seem to work. Here is what I have so far:
var item : GameObject;
var itemTransform : Transform;
var boneTransform : Transform;
function Start()
{
itemTransform = transform.Find("Item");
boneTransform = transform.Find("CharacterBone");
}
function OnTriggerEnter (theCollision : Collider)
{
if(theCollision.gameObject.tag == "Item")
{
itemTransform.parent = boneTransform;
}
}
This seems to work just if I assign the itemTransform and boneTransform by hand after the scene starts, but unfortunately that's not very convenient. Any ideas why the variables are not assigned on start?
Answer by meat5000 · Feb 20, 2015 at 04:10 AM
Drag your prefab into scene (and zero it).
Assign your transform by dragging it.
Drag the whole object back into a space in the Project Manager to create a prefab that is now set up.
Transform.Find finds a child object on that transform.
If you want to search through all objects use GameObject.Find instead.
$$anonymous$$aybe I'm not understanding what you mean, but when I set up the prefab and drag it back into the project manager, it does not seem to set up the prefab. The GameObject and Transform variables are set to "None (GameObject)" or "None (Transform)".
I am trying to find a child object on the character so
boneTransform = transform.Find("CharacterBone");
should work for that, but doesn't return anything.
And if I use
itemTransform = GameObject.Find("Item");
it says that I can't convert a transform variable to a gameObject variable.
Ah sorry, I think I misunderstood you.
You use your OnTrigger to compare the tag of the item. Why not use the reference you have right there within that function to manipulate the item ins$$anonymous$$d?
theCollision.transform.parent =
transform.Find works for the transform the script is attached to and will not find Grandchildren.
I figured out that you can use
itemTransform = gameObject.Find("Item").transform;
to get the transform of the gameObject. This solved my problem.
Using theCollision works too! Neat trick. Thanks for your help.