Friday, August 30, 2019

c# - How can I make a gameObject "stick" to another gameObject after it has collided with it?


How can I make a gameObject "stick" to another gameObject after it has collided with it? Right now the gameObject just passes through! [C#]



Answer



In the future, you could have easily found this with a search. It has been asked many times before and is a pretty simple thing to do. You will usually not get many good answers (or any at all) if you dont search some first =-)


However, with that said:


IIRC, if both of your game objects have colliders attached to them and you catch that collision, you can use:


object1.transform.parent = object2.transform


Your collison code would look something like the following (I havent tested this and havent used unity in a while so it may be off a little)


void OnCollisionEnter(Collision collision) {
collision.gameObject.transform.parent = gameObject.transform;
}

What the above does is takes the collided object and sets its transform to your current object. That way when your current object moves, the other one should follow along. You may get unexpected results if you have a rigid body attached to these objects too, but from what it sounds like, you dont


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...