- Home /
How to create cube made of cubes that are all fixed together?
I'm pretty new in Unity started about week ago.
I want to create cub (for example 3x3x3) that is made from cubes (1x1x1). I already got script that can do that, but the problem is with fixing it all together. I want to create this cube fixed with script, and when it touch specific objects all fixes will be destroyed and cube will fall apart.
I created basic cube (1x1x1) as prefab, and I give it to my sciript as parameter. But I don't know what's next. I tried smth like give component "FixedJoint" to all cubes starting from second one, and as fixed cube set the last one cube that was added to scene. But i got problems with that and I think that there can be easier solution.
Any suggestions?
Answer by N-8-D-e-v · Jul 17, 2020 at 11:07 AM
Just give them all rigidbodies, set them to kinematic, so they will not be affected by outside forces. Then, parent them all to an empty gameobject, which will serve as their pivot point (the object you will move to move the cube). Then, in a script attached to your pivot point (we can call this object cube), make an array of gameobjects, which will be your 1x1x1 cubes. If you haven't used arrays before, here's a good video explaining them https://www.youtube.com/watch?v=RQ0JHMGiobo TL:DR a gameobject array is a variable that stores multiple gameobjects, arrays can also store other data types, like box colliders, or floats. Then, you can loop through that array on a collision, like so
void OnCollisionEnter2D(Collision2D col)
{
for each(GameObject cube in cubes) //cubes is the array of gameobjects
{
cube.GetComponent<Rigidbody>().isKinematic = false;
}
}
this should do the trick, let me know if you have any more questions
Thanks! Thing I didn't know is that I can create another GameObject, set it as parent for small cubes and then use force on it so all cubes will move. Now it works how I wanted to :D
Your answer
Follow this Question
Related Questions
how avoid jiterring on fixed joints? 0 Answers
cube jump - script not working and with no errors 1 Answer
Cube trigger not changing position 0 Answers
How to change the selected image of a UI/Unlit/Transparent Material 0 Answers
How to make UI slider decrease in increments by 0.1f as each bullet is shot. using currentBullets--; 1 Answer