Creating an object and setting fields before object begins running

Hi folks,

I have what may be a simple “best practices” question that I haven’t seen a good answer for. Suppose I have ship objects and bullet objects, which are created by ship objects. I’d like each bullet to know the identity of the ship that created it. I’ve yet to find a satisfying way of doing this. Here are the things I’ve tried:

A) I had the ship create the bullet game object, and then immediately set the owner field in the bullet’s script to self. The problem is, as soon as I give the bullet object a script, that script starts running, so I have no way to ensure that the bullet’s owner field it set by the ship before the bullet script tries to access that field itself.

B) I had the bullet’s Start function wait for the owner field to be set, but this seems clumsy.

C) I could have the bullet try to set the owner field itself, but (i) this would require the bullet to somehow know which ship it was created by and (ii), even if that weren’t an issue, using Find feels similarly clumsy – the ship just created the bullet, shouldn’t the ship be able to pass along other information?

Thanks in advance for any suggestions on how to handle this more gracefully.


Do the initialization in Start() not Awake(). For example, create a prefab and put this script on a prefab:

#pragma strict

var id = -1;

function Awake() {
	Debug.Log("Awake: "+id);
function Start () 
	Debug.Log("Start: "+id);

Then put this script on an empty game object with ‘prefab’ initialized to the prefab you created above.

#pragma strict

var prefab : GameObject;

function Update() {

	if (Input.GetKeyDown(KeyCode.Space)) {
		var go = Instantiate(prefab) as GameObject;
		go.GetComponent(Test).id = 1;

When you hit the spacebar, you will see is that the value of ‘id’ will be -1 in Awake() but 1 in Start(). If this is not what you are experiencing, perhaps you want to post your scripts.