Hi, I’m making a 2d game with:
Enemy prefab
Enemy bullet prefab
I want the bullets to be instantiated at a scale in proportion to the scale of the enemy that fired it & am having trouble passing the scale of the enemy across to the bullet.
The code on the bullet that relates to it is:
Bullet Code
public float speed;
float desiredScaleRate = 1.018f;
// scale variables
public E_Rotate_Ship shipScale;
public GameObject Self1;
// Use this for initialization
void Start ()
{
shipScale = Self1.gameObject.GetComponent<E_Rotate_Ship> ();
//set size of bullet
transform.localScale = new Vector3 (transform.localScale.x / shipScale.enemyScale.x, transform.localScale.y * shipScale.enemyScale.y, 1);
// destroy the bullet after 2 seconds
Destroy (gameObject, 2f);
}
The enemy is changing it’s size each update & the code on the enemy tracking its scale for use by the bullet is:
Enemy scale
// Set variable for use by bullet
public Vector3 enemyScale;
// Update is called once per frame
void Update () {
// set value of variable for use by bullet script
enemyScale = transform.localScale;
}
In the bullet prefab inspector I have used the enemy prefab as Self1 & referenced the script on the enemy that is updating its scale & triggering the bullet.
The problem I’m having is that in debug the enemy is updating the enemyScale correctly but on the bullet prefab it is using the scale of (0,0,0). Any suggestions on how I can get the correct scale to be passed across?
In line 13, shipScale = Self1.gameObject, is redundant specifically at “Self1.gameObject”, you already have Self1 as a gameObject, so you’re saying gameObject.gameObject
I’m not sure how you have your scaling working, but this line seems a little strange.
new Vector3(transform.localScale.x/ shipScale.enemyScale.x, transform.localScale.y* shipScale.enemyScale.y, 1);
In terms of keeping the scale in respect of the enemy ship, wouldn’t you want something such as…
new Vector3(enemyScale.x * desiredScaleRate, enemyScale.y * desiredScaleRate, enemyScale.z * desiredScaleRate)
In terms of performance, for the enemyScale function in the second snippet. You have enemyScale = transform.localScale. If you are planning on changing the scale of the enemy all the time this is appropriate. However I would recommend moving that to the Start() function. So you’re not wasting that processing for each enemy.
Thanks for responding. Yes I was scaling that enemy every turn.
I eventually worked out that the bullet must’ve been taking the scale from the prefab itself & not the enemy(clone) that fired the bullet. I got it to work by casting the instantiate to an GameObject obj, setting that obj scale to the scale of the enemy, then scaling the bullet during its start function.