- Home /
Setting a Prefab Clone as the Child of another Object on Collision (2D)
I am making a 2D Fishing Game, in which I am trying to have a Fish Prefab Clone become the Child Object of a Hook Object when they Collide. I have looked at a number of varying tutorials all of which don't seem to apply or work. This is the code I currently have, any ideas would be appreciated greatly.
public GameObject GreyFish;
void OnTriggerEnter2D(Collider2D collision)
{
if(collision.gameObject.tag == "GreyFish")
{
GreyFish.transform.parent = transform;
}
}
I assume this script is attached to the Hook Object? Inside your if statement do:
collision.transform.parent = transform;
Answer by Reid_Taylor · May 14, 2020 at 04:33 PM
Well your code is kinda confusing but ill try and understand it.
First if all i'm guessing this is the fishing hook script in which it test for collision with fish. I can't really figure out the need for the GameObject GreyFish
. Im pretty sure your code should look like this though
public GameObject GreyFish;
void OnTriggerEnter2D(Collider2D collision)
{
if(collision.gameObject.tag == "GreyFish")
{
GreyFish = collision.gameObject;
GreyFish.transform.parent = transform;
}
}
I think its because public GameObject GreyFish
isn't set yet.
But you could also just do it like this...
void OnTriggerEnter2D(Collider2D collision)
{
// Compare tag method is more performant
if (collision.gameObject.CompareTag("GreyFish"))
{
collision.transform.parent = transform;
}
}
(Code not tested) Lemme know if i'm wrong...
Thanks this works for a new GameObject with the Tag, but It doesn't seem to work with a Clone generated from a Prefab with the Tag, the Hook GameObject just passes through.
$$anonymous$$ake sure the prefab has same tag and components.
The only difference is a Rigidbody 2D component which is being used in a $$anonymous$$ovement script for the Fish