How can I translate the JS code into C Sharp code?

Hi,
I want to add the script below to Animation’s event since it is written in JS. Could anyone help me out to translate (convert) this script into C Sharp?

#pragma strict
var parentbone:GameObject;
var rigid:Rigidbody;
var lastPos.Vector3;
var curVel.Vector3;

function Start()
{
transform.parent=parentbone.transform;
rigid.useGravity=false;
}

function ReleaseMe()
{
transfor.parent=null;
rigid.useGravity=true;
transform.rotation=parentbone.transform.rotation;
rigid.AddForce(transfor.forward*2000);
} 
1 Like

I saved the naming of your variables, but it is not suitable for Identifier names - rules and conventions - C# | Microsoft Learn , so parentbone must be parentBone, for example.

using UnityEngine;

public class NewBehaviourScript : MonoBehaviour
{
    [SerializeField]
    private GameObject parentbone;

    [SerializeField]
    private Rigidbody rigid;

    private Vector3 lastPos;
        
    private Vector3 curVel;

    private void Start()
    {
        transform.parent = parentbone.transform;

        rigid.useGravity = false;
    }

    private void ReleaseMe()
    {
        transform.parent = null;

        rigid.useGravity = true;

        transform.rotation = parentbone.transform.rotation;

        rigid.AddForce(transform.forward * 2000f);
    }
}

1 Like

Thank you so much Andrey!

1 Like

I also have this javascript:

#pragma strict
var theball:GameObject;

function ThrowBall()
{
    var ballscript:BallScript = theball.GetComponent("BallScript");
    ballscript.ReleaseMe();
}

That I tried to convert it into:

public class ThrowBall : MonoBehaviour
{
    [SerializeField]
    public GameObject theBall;

    public Releaseme ballScript;

    public void Throwball()
    {
        ballScript = theBall.GetComponent<Releaseme>();

    }
}

I hope I did it right :blush:

[SerializeField] public — it is redundant.

You can use public modifier without attribute to expose variable in inspector.

or use [SerializeField] private to expose the same way but without access outside the class via code.

1 Like