- Home /
Attaching 2 object
I need help about attaching a cylinder and a sphere. I'm trying to swing that cylinder by rotating sphere but when I rotate sphere cylinder doesn't get affected.
public GameObject cylinder;
public Transform sphere;
public void yelpaze(Transform newParent)
{
cylinder.transform.SetParent(newParent);
cylinder.transform.SetParent(newParent, false);
cylinder.transform.SetParent(null);
}
I tried this after an advice but still doesn't work.
cylinder.transform.SetParent(newParent);
should be enough. cylinder.transform.SetParent(null);
detaches the cylinder from its parent.
Answer by Duckocide · Oct 25, 2020 at 11:45 AM
Hi @ozgunn
I'm not sure what your method is trying to achieve as your assigning then un-assigning the parent transform for the cylinder. Any hoo, I'm guessing you're trying to get the cylinder to swing back and forth under the sphere.
You can of course make the cylinder a child of the sphere in the editor. Here goes.
Add the sphere to your scene
Add the cylinder to your scene and make it a child of the sphere (drag the cylinder over the sphere) - This is the same as the SetParent code you have written.
Adjust the cylinder position to where you want it.
Add the script below to the sphere
Run
public class SwingCylinder : MonoBehaviour {
private Vector3 _originalLocalEulerAngles;
// Start is called before the first frame update
void Start()
{
_originalLocalEulerAngles = transform.eulerAngles;
}
// Update is called once per frame
void Update()
{
// In start() we grabbed the current angles for this gameObject. So, we can now add a sinusoidal (pendulum) swing to them
// on the z-axis (Vector3.forward) ... I.e. Axis simplistically through the screen (in world space)
// The formula basically uses the prevailing time in seconds as a radian value in the Sin (Sine function).
// We multiply this by 60 (degrees) so the swing oscillates between -60 and 60
transform.eulerAngles = _originalLocalEulerAngles + (Vector3.forward * Mathf.Sin(Time.time) * 60f);
}
}
![alt text][2]
[2]: /storage/temp/169836-editor3.jpg
thx very much @Duckocide. Even I don't know why I have written that code. But now I get it how to swing my object thanks to you.
Your answer
Follow this Question
Related Questions
Adding A Script To A Scene 2 Answers
Attach a GUI Skin Dynamicaly 2 Answers
How to 'gravitize' an object/camera to another sphere... 1 Answer
How do i create an object with a GUI Button 1 Answer
Attaching an object to a camera movement weird, Help! 2 Answers