- Home /
In Unity how can I set a value to property while initializing a prefab with Instantiate() method like OOP constructor with parameters?
I am a newbie in Unity and game development. I want to make a mobile stack jump game with primitives. I have a player in the center of the screen. The enemy is approaching the player from the right and left of the screen. The player tries to sit on the enemy by jumping as in Mario Game. If the enemy hits the player from the side, the game is over. I create enemies with a SpawnMan. There is a prefab for an enemy game object. SpawnMan creates them at certain time intervals with the Instantiate() method. I want to store data on whether the enemy is approaching from right or left. I even want to store this information by creating an enum type. In summary, I want to have enemy objects with the left and the right types. How do I set this property (left enemy or right enemy) when calling the Instantiate() method in SpawnMan as in OOP constructor with parameters.
enum EnemyType
{
Left,
Right
}
// ...
Instantiate(enemyPrefab(EnemyType.Left), spawnPos, enemyPrefab.transform.rotation);
Answer by Llama_w_2Ls · Apr 01, 2021 at 11:46 AM
You can't really do this with instantiate by itself, because instantiate only controls the spawning of the game object. The scripts, however, can be modified using GetComponent
. Here's an example:
var enemy = Instantiate(enemyPrefab, spawnPos, enemyPrefab.transform.rotation);
enemy.GetComponent<EnemyScript>().enemyType = EnemyType.Left;
Your EnemyScript should look something like this:
public class EnemyScript : MonoBehaviour
{
public EnemyType enemyType;
//...
}
As long as the EnemyScript is directly attached to the enemyPrefab, GetComponent should be able to modify the EnemyType. Hope that helps. @fxgamesstudio