A simple Unity C# script to follow any object’s position and rotation



I call this script “Stick with It”. With this C# script you can parent any object to an object with more options such as setting up position offsets and specifying what rotation axis is needed or not.

Here is the script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class StickWithIt : MonoBehaviour
{
	
	public GameObject anyobject;
	public Vector3 offset;
	
	public bool followXRot = true;
	public bool followYRot = true;
	public bool followZRot = true;
	
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        anyobject.transform.position = transform.position + offset;
		float xRot = 0f;
		float yRot = 0f;
		float zRot = 0f;
		if(followXRot)
			xRot = transform.eulerAngles.x;
		if(followYRot)
			yRot = transform.eulerAngles.y;
		if(followZRot)
			zRot = transform.eulerAngles.z;
        anyobject.transform.eulerAngles = new Vector3(xRot, yRot, zRot);
    }
}

loading...

Leave a Reply

Your email address will not be published. Required fields are marked *