How Do I Programatically Attach Objects To Each Other?

Hello. I am trying to programatically attach objects to each other so they behave as one object when attached. Forgive me if this question has already been asked but I couldn't find a suitable answer on here to help me out. If I missed it please kindly point me in the right direction. I am very new to programming and am using C# so example code would be appreciated.

Ok so here's what I'm trying to do...

I have a bunch of blocks (cubes) that I would like to randomly attach to each other in code to form various shapes (like Tetris pieces). When attached, these newly formed shapes should act as a single object and be able to be dragged around as a solid shape without breaking apart. They should still visually appear as composed of the initial cubes that made them up (just stuck together in various shapes).

I don't know if that is clear enough but any help would be greatly appreciated. Thank you.

3 Answers

3

Set transform.parent = otherObject.transform to attach this object to the other object for example.

When attaching objects, I also found it useful to disable collisions on the object being attached. For example:

// Disable collisions with the object being attached
if(Object1.collider2D)
{
	Object1.collider2D.enabled = false;
}

// Don't allow physics to affect the object
if(Object1.rigidbody2D)
{
	Object1.rigidbody2D.isKinematic = true;
}

// Attach object 1 to object 2
Object1.transform.parent = Object2.transform;

// Center object 1 on object 2 (no offset)
Object1.transform.localPosition = Vector3.zero;

Thanks, this helped my attached objects to stay still when i applied force to the parent.

Just make sure that you watch the relative positions & rotations.

I have:

GameObject objA=...;
GameObject objB=...;
// attach a to b
objA.transform.parent=objB.transform;
// make sure its exactly on it
objA.transform.localPosition=Vector3.zero;
objA.transform.localRotation=Quaternion.identity;

And its fine.

it doesn't work for me any suggestions?

Be more specific than 'its broken' Explain whats the matter & I might be able to advise.