Is there a way to assign variables before Awake() is triggered
I want to assign a variable before Awake() is triggered. Is there a way?
In this example It gets triggered before i can assign it.
HeightMap_Data retVal = gameObject.AddComponent<HeightMap_Data>();
retVal = new HeightMap_Data
{
game = gameObject
};
Answer by Hellium · Jul 17, 2018 at 07:18 AM
This is not possible if you use the AddComponent
or Instantiate
functions.
I see two solutions to your problem:
In your HeightMap_Data
script, move the content of your Awake
function in the Start
method. You will be able to assign the variables, and Start
will be called afterwards.
In your HeightMap_Data
script, move the content of your Awake
function in a custom method called Initialize
for example, taking a parameter, and assigning the values you want.
HeightMap_Data retVal = gameObject.AddComponent<HeightMap_Data>();
retVal.Initialize( gameObject ) ;
// Initialize method inside HeightMap_Data
public void Initialize( GameObject go )
{
this.game = go ;
// Content of the Awake method
}
I think i tried to make Awake() into Start() but it wierdly behaved the same :/ . I sloved the problem by going with another method that does what Awake() did and deleted Awake()
Answer by tormentoarmagedoom · Jul 17, 2018 at 06:33 AM
Good day.
Awake is the first method to be called in a script, so if you want a method to be called before "Awake A", the only option is to make another Awake method in another script, Awake"B" to run before the "Awake A". In that "Awake B" you can call a void method of the "Script A" that define the variables.
The other option is to assign the variables via inspector, so they are already assigned when Awake is executed.
But, let me ask... Why you need this? Why dont make all the Awake things in another method like OnEnable() or Start() ?
Bye!!
Answer by Florian-Nouviale · May 19, 2020 at 11:49 AM
You can if you deactivate the GameObject first :
gameObject.SetActive(false);
YourComponent component= gameObject.AddComponent<YourComponent>();
// Assign Variables here
gameObject.SetActive(true);