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;
}
}
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…