How to do things before Awake? Objects constructors
- thetperson314
- Dec 10, 2021
- 1 min read
Usually then we instantiate objects in Unity the first thing to happed is the
For this example we have a Cube and a GameManager.
For the Cube we will create a CubeScript with the values for speed and rotation, a constructor function and we will use the speed and rotation too (but it's not relevant for right now).
public class CubeScript : MonoBehaviour
{
float speedX = 0;
float rotationY = 0;
public void SetUp(float speedX, float rotationY)
{
this.speedX = speedX;
this.rotationY = rotationY;
}
void Start()
{
this.GetComponent<Rigidbody>().velocity = new Vector3(speedX,0,0);
}
void Update()
{
this.transform.Rotate(new Vector3(0, rotationY, 0));
}
}
For the GameManager we will create a script called InstantiateManager.
in this script we will call the cube gameobject, use the setup function and then instantiate it
public class InstantiateManager : MonoBehaviour
{
[SerializeField]
GameObject cube;
void Start()
{
cube.GetComponent<CubeScript>().SetUp(1, 1);
Instantiate(cube.gameObject);
}
}Extra:
In the InstantiateManager, if you use the SetUp function right after you instantiate the object, and not before, the function will happened after Awake & OnEnabled but will happened before Start.
