- Home /
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?
Answer by sykodev · Apr 11, 2015 at 03:20 PM
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.
Answer by KalleH · Apr 11, 2015 at 11:56 AM
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.
For some odd reason, if I substitute this line:
GameObject g = Instantiate (projectilePrefab, spawnPos, faceRotation) as GameObject;
with this:
Transform g = Instantiate (projectilePrefab, spawnPos, faceRotation) as Transform ;
It works. Basically, the same line, but ins$$anonymous$$d of GameObject, I use a Transform. Weird, isn't it?
And good call--accessors & getters is good practice, and that's actually my intention, but I wanted to simplify the code as much as possible for getting the question answered first. :)
That sounds pretty weird indeed, I have never seen anything like that happen. What does your prefab consist of? Gameobject with a script and a collider attached to it?
Your answer
![](https://koobas.hobune.stream/wayback/20220613192740im_/https://answers.unity.com/themes/thub/images/avi.jpg)