I am trying to Instantiate a Prefab and manipulating an attribute before i call the Instantiate() function. This is because each Prefab I instantiate is meant to have a different behaviour type.
Please Help :)
I am trying to Instantiate a Prefab and manipulating an attribute before i call the Instantiate() function. This is because each Prefab I instantiate is meant to have a different behaviour type.
Please Help :)
Typically you would make any necessary modifications to the instance immediately after instantiation. (You can use the return value of Instantiate() to access the instance.)
Like Jesse said, you can access attached scripts after instantiate with GetComponent() or add new scripts with AddComponent(). Just keep in mind what events are fired first.
Two little test scripts. A gun and a bullet script. The bullet script is attached to the bullet prefab.
//gun
var bulletPrefab : Transform;
private var logNextUpdate : boolean = false;
function Update () {
if (logNextUpdate)
{
Debug.Log("Gun:next Update() after instantiate");
logNextUpdate = false;
}
if (Input.GetKeyDown(KeyCode.W))
{
logNextUpdate = true;
Debug.Log("Gun:Update()");
var BulletShot = Instantiate(bulletPrefab, transform.position, transform.rotation);
Debug.Log("Gun:Update:Instantiate done");
}
}
//bullet
private var logFirstUpdate : boolean = true;
function Awake() {
Debug.Log("Bullet:Awake");
}
function OnEnable(){
Debug.Log("Bullet:OnEnable");
}
function Start() {
Debug.Log("Bullet:Start");
rigidbody.AddForce(transform.forward * 1000);
}
function Update () {
if (logFirstUpdate) {
Debug.Log("Bullet:Update first run");
logFirstUpdate = false;
}
}
You will get this order:
As you can see Awake and OnEnable are triggered immediately when you instantiate your object. Use Start() if your object needs to do some initialization. That way you can easily setup some variables on the new created object before it initializes itself.
you could possibly make several prefabs with the different options already set and include an array for the different prefabs in the spawner script