20 Useful lines of code that can be used for C# scripting in Unity | pt:1
Rizmy Abdulla 🎖️ ・ Dec 10 '22
1.To instantiate an object at a specific position and rotation:
GameObject object = Instantiate(prefab, position, rotation);
2.To access the components of a GameObject:
Rigidbody rb = gameObject.GetComponent<Rigidbody>();
3.To move a Rigidbody in the direction it is facing:
rb.velocity = transform.forward * speed;
4.To rotate a Rigidbody towards a target position:
Vector3 direction = target.position - transform.position;
rb.rotation = Quaternion.LookRotation(direction);
5.To apply a force to a Rigidbody in a specific direction:
rb.AddForce(direction * force);
6.To set the position of a Transform:
transform.position = new Vector3(x, y, z);
7.To set the rotation of a Transform:
transform.rotation = Quaternion.Euler(x, y, z);
8.To set the scale of a Transform:
transform.localScale = new Vector3(x, y, z);
9.To find an object in the scene by name:
GameObject object = GameObject.Find("ObjectName");
10.To find an object in the scene by type:
GameObject object = GameObject.FindObjectOfType<Rigidbody>();
11.To destroy a GameObject:
Destroy(gameObject);
12.To destroy a GameObject after a delay:
Destroy(gameObject, delay);
13.To set the value of a public variable in another script:
otherScript.variableName = value;
14.To invoke a method in another script:
otherScript.MethodName();
15.To check if a key or button is pressed:
if (Input.GetKeyDown(KeyCode.Space))
{
// Perform action
}
16.To get the current frame rate
float frameRate = 1 / Time.deltaTime;
17.To load a scene by name:
SceneManager.LoadScene("SceneName");
18.To add a new entry to a Dictionary:
Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("Key", value);
19.To check if an object is in a List:
List<GameObject> list = new List<GameObject>();
if (list.Contains(object))
{
// Object is in the list
}
20.To sort a List by a property of the objects in the list:
list.Sort((a, b) => a.name.CompareTo(b.name));
Thanks For reading...
Top comments (0)