Hi all, I have a scene where on mouse press, a cannonball is fired from a cannon and force is applied using ForceMode.Impulse using the angle and rotation of the cannon prefab and corresponding spawn point. Everything works exactly as required. Because this is a physics game, I need the cannonballs to all use the appropriate physics once fired and they currently do so. However, if I click to fire another cannonball, that works correctly, but the same force is applied to any previously fired balls. I’ve tried changing the names of the clones, setting flags on the instantiated balls, etc. and I am sure I am just not doing it correctly, but can’t for the life of me figure out what to do. Any help would be greatly appreciated. Here is the code that works for firing the cannonballs.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CannonController : MonoBehaviour {
public GameObject projectilePrefab;
private List<GameObject> Projectiles = new List<GameObject>();
public Transform spawnLoc;
private Vector3 spawnPos;
public float maxVelocity;
public float projectileVelocity;
void Start () {
spawnPos = new Vector3(spawnLoc.position.x, spawnLoc.position.y, spawnLoc.position.z);
}
void Update () {
if (Input.GetMouseButtonDown(0))
{
CannonShot();
}
}
void CannonShot()
{
GameObject ball = (GameObject)Instantiate(projectilePrefab, spawnPos, spawnLoc.rotation);
Projectiles.Add(ball);
for (int i = 0; i < Projectiles.Count; i++)
{
GameObject goBall = Projectiles[i];
if (goBall != null )
{
goBall.GetComponent<Rigidbody2D>().AddForce(spawnLoc.transform.right * projectileVelocity, ForceMode2D.Impulse);
goBall.GetComponent<Rigidbody2D>().velocity = Vector3.ClampMagnitude(goBall.GetComponent<Rigidbody2D>().velocity, maxVelocity);
}
}
}
}