top of page

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.


 
 

Recent Posts

See All

FAVORITES

Try playing Core Keeper and learn from it's sound design!

From the sound effect to the music - this is a masterpiece!

WHAT'S NEW?

New game on Steam and a new mobile video asset are soon to be published!!

I AM THINKING ABOUT

AI is on the rise. Being able to use it in the right cases and explaining the task correctly is no easy task but once you finish a full task without writing a line of code - your world will change!

CONTACT ME

Use any social media to contact me. For any question about programing and project I prefer using my Discord server, See you there!

© 2021 by Amit Klein. Nerd Head.

bottom of page