GameObject
Base class for all entities in Unity Scenes, called GameObjects. Let's take a look at some things we can do with them.
Accesing the gameObject name:
void start() {
Debug.Log(gameObject.name);
}
To call outside GameObjects, we have to declare the GameObject variable:
public GameObject myCube;
void start() {
Debug.Log(myCube);
}
To search for a game object:
public GameObject SearchingCubes;
void start() {
SearchingCubes = GameObject.find("cube");
}
If there are more objects, it's possible to search for them using tags, and add them to array.
public GameObject[] cubes;
void start(){
cubes = GameObject.FindGameObjectsWithTag("Redcubes");
}
Components
A component is a base class for everything attached to GameObjects.
For this example I will access the component transform of the GameObject through the script.
( ! )
Notice that the script.cs is now a component of the GameObject, so now I can call it by just writing gameObject
.
public class MyComponent : MonoBehaviour {
void Start() {
Debug.Log(gameObject.transform.position.x);
}
}
Example: Calling only x and z.
public class MyComponent : MonoBehaviour {
void Start() {
float x = gameObject.transform.position.x;
float z = gameObject.transform.position.z;
Debug.Log($"{x + z}");
}
}
This way only works if the script is a componet of the same GameObject. To know the transform values of another GameObject, like a Camera, we need to save that GameObject to a variable first. This script will return the x position of myCameraTransform
.
public class MyComponent : MonoBehaviour {
public Transform myCameraTransform;
void Start() {
Debug.Log(myCameraTransform.position.x);
}
}
Example: Enabling the component BoxCollider. In this case, the component will be assigned automatically through the script with GetComponent<BoxCollider>()
.
public class MyComponent : MonoBehaviour {
public BoxCollider myCollider;
// Start is called before the first frame update
void Start() {
myCollider = GetComponent<BoxCollider>();
myCollider.enabled = true;
}
}
( ! ) GetComponent<>(); works for all components.