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.
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);
}
}
