- Home /
How to differentiate between prefabs on collision.
I have several character prefabs created one at a time. The prefabs move on their own through a stage. When a character collides with an object I need them to pick it up (it attaches to a mount in their hierarchy). I have this working just fine except for when the second prefab is created.
If the second prefab touches the object, it becomes attached to the first prefab's mount instead of the one that touched it. I'm not sure how I am supposed to tell the object which prefab is which. Here is the script I currently have.
var itemTransform : Transform;
var mountTransform : Transform;
function Start()
{
itemTransform = gameObject.Find("Item").transform;
mountTransform = gameObject.Find("Mount").transform;
}
function OnTriggerEnter (theCollision : Collider)
{
if(theCollision.gameObject.tag == "Item")
{
theCollision.transform.parent = mountTransform;
}
}
I'm guessing this script is attached to the character prefab, so it fires the OnTriggerEnter(Collider other)
, so ins$$anonymous$$d of using a variable just use other.transform.SetParent(transform)
. You have a transform variable referencing to an Item which is not needed. Also you should use GameObject.FindGameObjectWithTag("Item")
(That's for C#, use the JS equivalent).
Oh yeah, whoops. I was using
itemTransform.transform.parent = mountTransform;
but switched it the use theCollision and just forgot to remove that variable.
I'm a little confused on how to use the SetParent function. I looked at the documentation, but it doesn't really give an example of how to use it. Could you explain it a bit further or maybe point me to a tutorial that does? Sorry if I'm missing something obvious. This is still my first project.
Answer by SBull · Feb 23, 2015 at 08:17 PM
I figured out how to make it work. Using
mountTransform = transform.Find("hierarchy/path/to/mount");
This was actually the first thing I tried, but couldn't get it to work because I put the entire path including the name of the prefab object. By dumb luck I randomly decided to drop the top level of the hierarchy and just start listing from the armature and it worked like a charm.