Refer to Object that Instantiated this Object

I have a VERY long damage script attached to my bullet, which is instantiated by any player or enemy in the game. However, i need to access a script on the object who instantiated the bullet from the damage script to get attack statistics(attack strength). How should I access the shooter if i plan to make this bullet and script a prefab that would work for any player or enemy i attach it to? I can’t use tags, as two players may be shooting at once. What can I do?

1 Answer

1

Just add a variable to the bullet script telling it who’s its father (a kind of DNA variable), then assign to it the creator’s transform.

In the bullet script (let’s call it BulletScript.js):

var daddy: Transform; // create the DNA variable
    ...
    // when the bullet need to communicate with the father script:
    var dadScript: FatherScript = daddy.GetComponent(FatherScript);
    // now you have a reference to the script in dadScript
    ...

Fill the daddy variable when creating a new bullet:

    var bullet = Instantiate(bulletPrefab, ...);
    bullet.GetComponent(BulletScript).daddy = transform;

I agree with aldonalettos solution! Anyway I would suggest to pass any important attack statistics (velocity, direction, strength) from father to child, instead the other way around. It's not really best practice if the bullet has a reference to the shooter and can access his properties.

bullet.transform.parent = someTransform; or are you not talking about transform parenting here?

Listen to Thomas. Making the bullet a child of the attacker will destroy your bullet along with the attacker, should he die before the bullet hits. Reading the properties from the attacker will also probably cause a missing reference under the same circumstances. I'd strongly advise against this.