I’m trying to create a two-player tank battling game and have come a bit stuck. For each tank I want to track the number of bullets left to prevent them from firing too many. Each instance of the tank is referring to a single script called TankShooting, inside of which is a variable called bulletCount that I use to track the number of bullets remaining.
My question is this: Is there a way for me to assign this variable a different value for each of the Tank instances in the scene?
For example, I’ll start by giving tanks Tank1 and Tank2 three bullets each. If Tank1 fires a bullet, I want to decrease its value of bulletCount by 1 , while keeping the value of bulletCount for Tank2 the same (i.e. 3).
Thank you so much if anyone is able to help me out with this. I really appreciate it!
Here’s a copy of my TankShooting script:
using UnityEngine;
using UnityEngine.UI;
public class TankShooting : MonoBehaviour
{
public int m_PlayerNumber = 1; // Used to identify which player called the script
public Rigidbody m_Shell; // The prefab of the shell
public Transform m_FireTransform;
public float m_LaunchForce = 30f;
private string m_FireButton;
private bool m_Fired;
public int m_BulletCount = 3;
private void OnEnable()
{
}
private void Start()
{
Debug.Log ("Bullet count at start = " + m_BulletCount);
m_FireButton = "Fire" + m_PlayerNumber;
}
private void Update()
{
if (Input.GetButtonDown (m_FireButton)) {
Fire ();
}
}
private void Fire()
{
if (m_BulletCount > 0) {
// Instantiate a shell and launch it.
Rigidbody shellInstance = Instantiate (m_Shell, m_FireTransform.position, m_FireTransform.rotation) as Rigidbody;
// Set the shells velocity to the value of m_LaunchForce in the direction the tank is facing
shellInstance.velocity = m_LaunchForce * m_FireTransform.forward;
} else {
Debug.Log ("Not enough bullets left to fire!");
}
}
public int getBulletCount() // Returns the current value of m_BulletCount as an integer
{
return m_BulletCount;
}
public void setBulletCount(int value) // Sets m_BulletCount to a specific value
{
m_BulletCount = value;
}
public void incrementBulletCount(int value) // Increment m_BulletCount by the increment specified
{
Debug.Log (m_BulletCount);
m_BulletCount = m_BulletCount + value;
}
}