Modify property of an instantiated object

I’m creating a simple projectile system.

		GameObject g = Instantiate (projectilePrefab, spawnPos, faceRotation) as GameObject;
		GameProjectile proj = g.GetComponent<GameProjectile> ();
		proj.damage = 30f;

Then in the GameProjectile code, I have:

public float damage;

void Update() {
    print ("damage = " + damage);
}

However, this keeps printing out 0, instead of 30.

How can I fix my code such that it will print out 30?

For simplicity, you could do:

GameProjectile projectile = Instantiate (projectilePrefab, spawnPos, faceRotation) as GameProjectile;
p.damage = 30f;

As far as your damage not being set… it IS getting set, but you may have another script overriding that value, or a typo on a different line of code where it’s used. I suggest checking everywhere you use the “damage” float and making sure things are as they should be.

Your script should work just well and I even tried it out without any problems. Make sure that every class name is spelled correctly and that you don’t have an active instance of GameProjectile already in scene view (if you do, it will print 0 since you never change its damage, only the instantiated versions’). Also make sure that the GameProjectile script is attached to the root gameobject and not any child or else you will have to edit your code a bit.

If you are still having trouble getting it work you could create a public variable proj for GameProjectile in the first script instead of using a temporary one. This allows you to see in editor that the script finds the GameProjectile component correctly. I highly believe that the reason for your script failing is related to finding that component.

If the damage is always the same you could also just simply add damage = 30 to void Start() function in your GameProjectile. I also recommend not changing variables of other scripts directly from another script and instead create a function in GameProjectile like public void setDamage(float value) which you can simply call from another script.