Search Unity

Question Combining Objects in game

Discussion in 'Editor & General Support' started by Daoxin7, Jan 3, 2024.

  1. Daoxin7

    Daoxin7

    Joined:
    Oct 20, 2017
    Posts:
    5
    Hey there so having issues when combining two objects together when a collision happens.

    I am making a pendulum set with the 3D materials in unity. When I have my rod enter a certain area on the face place, the rod turns sideways, becomes flat, and spins around like a campus. I do not want that to happen. I want it to merge and stay together.

    I want to use the same script to help assemble a pendulum set so it is pretty vague. I'm also doing this in VR headsets and all, but I doubt that it is affecting it at all.

    I have the all my game objects in an empty game object. They are all children and when it comes to the metal plate it is the base and the target and rod are it's children
    penSetUp.PNG

    This what it looks like before the collision
    beforetheDisaster.PNG


    This is what happens after it collides the original area that needs to be inserted to
    RodSideways.PNG


    Here is the code I have. So what I am doing is self-explanatory where I have two objects that are being targeted and should have the rod inside the origin object and also have a fixed joint so it does not spin.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using Unity.VisualScripting;
    4. using UnityEngine;
    5.  
    6.  
    7. public class AttachItem : MonoBehaviour
    8. {
    9.     [Header("boolean test")]
    10.     public bool isAttached = false;
    11.  
    12.     [Header ("Original Object")]
    13.     public GameObject originGameObject;
    14.  
    15.     [Header("Object to be attach with")]
    16.     public GameObject targetGameObject;
    17.     public Vector3 targetedPos;
    18.  
    19.     private void OnCollisionEnter(Collision collision)
    20.     {
    21.         if(collision.gameObject.GetComponent<Rigidbody>() != null && !isAttached)
    22.         {
    23.             targetGameObject.AddComponent<FixedJoint>();
    24.             targetGameObject.GetComponent<FixedJoint>().connectedBody = originGameObject.GetComponent<Rigidbody>();
    25.  
    26.             // Set the position and rotation of targetGameObject relative to originGameObject
    27.             targetGameObject.transform.position = targetGameObject.transform.TransformPoint(targetedPos);
    28.             targetGameObject.transform.rotation = originGameObject.transform.rotation;
    29.  
    30.  
    31.             isAttached = true;
    32.         }
    33.     }
    34.  
    35. }

    What looks like after making the script

    thescriptComponent.PNG