📜  trnasform ubnity - C# (1)

📅  最后修改于: 2023-12-03 15:05:37.869000             🧑  作者: Mango

Transform Unity - C#

Introduction

Transform is a fundamental component in Unity that represents the position, rotation, and scale of an object in 3D space. In C#, you can access and manipulate the Transform component through scripts to change an object's position, rotation, and scale.

Accessing the Transform Component

The Transform component can be accessed through the transform property of any GameObject in Unity. Here's an example of accessing a GameObject's Transform and changing its position:

// Access the Transform component
Transform myTransform = gameObject.transform;

// Change the position of the object
myTransform.position = new Vector3(1, 2, 3);
Manipulating the Transform Component

To manipulate the position, rotation, or scale of a GameObject's Transform, you can use the following properties:

  • position: the position of the object in 3D space
  • rotation: the rotation of the object in 3D space
  • scale: the scale of the object in 3D space

Here's an example of manipulating a GameObject's Transform to rotate it around the Y-axis:

// Access the Transform component
Transform myTransform = gameObject.transform;

// Rotate the object around the Y-axis
myTransform.rotation *= Quaternion.Euler(0, Time.deltaTime * 90, 0);
Parenting and Hierarchy

In addition to representing an object's position, rotation, and scale, the Transform component also represents an object's place in the hierarchy of the scene. You can set a GameObject's parent to create a parent-child relationship, which affects the position and rotation of the child object relative to its parent.

To set a GameObject's parent, you can use the Transform.SetParent() method:

// Access the Transform component of the child object
Transform childTransform = childObject.transform;

// Set the parent of the child object to the parent object
childTransform.SetParent(parentObject.transform);
Conclusion

The Transform component is an essential part of Unity and allows you to manipulate the position, rotation, and scale of a GameObject in 3D space. With this knowledge, you can begin to create dynamic and interesting scenes in your Unity projects.