- Home /
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.
Answer by DaveA · Apr 15, 2011 at 05:31 AM
Set transform.parent = otherObject.transform to attach this object to the other object for example.
Answer by SpacePilot1000 · Apr 05, 2014 at 04:55 AM
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.
Answer by mark.gossage · May 22, 2012 at 02:14 AM
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.
Be more specific than 'its broken' Explain whats the matter & I might be able to advise.
Your answer
Follow this Question
Related Questions
Attach object when NOT in Hierarchy 1 Answer
Question about animation 2 Answers
How can I attach objects like a picture? 2 Answers
Calling 2 objects into script for onCollisionEnter? 1 Answer