Ammo UI doesn’t update after respawn

Updated on November 26, 2018 in [A] GUI
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
8 on November 21, 2018

Hey there, I followed one of brackeys tutorials and now am adding more content to the project, but I ran into an issue i don’t seem to be able to understand what’s the cause.

So I created a basic script to update the text:

 

using UnityEngine;
using UnityEngine.UI;

[RequireComponent(typeof(Text))]
public class CurrentAmmo : MonoBehaviour {

[SerializeField]
private Text curAmmoText;

private WeaponSwitching weaponS;
private Weapon pistol;
private WeaponMachinegun machinegun;

void Awake() {

curAmmoText = GetComponent<Text>();

}

void Start() {

weaponS = WeaponSwitching.weaponSwitch;
pistol = Weapon.instance;
machinegun = WeaponMachinegun.wMachine;

}
void Update() {

if (weaponS.isPistol == true) {
curAmmoText.text = pistol.curAmmo.ToString();
}
if (weaponS.isMachinegun == true) {
curAmmoText.text = machinegun.curAmmo.ToString();
}

}
}

 

and it works as intended

but seems to only work for my first clone, after respawn it stops working properly.

 

 

I made the script part of the UI like this:

So I don’t get why it stops updating since the player prefab is exactly the same as the one respawning

Thank you for your time

  • Liked by
Reply
0 on November 21, 2018

Can I see your weapon scripts?

I think it has something to do with how you’re getting their references on start only, and never updating them to the new weapons.

 

One thing you might want to think about, is instead of generating a new player when they re-spawn, just move their current player to the spawn point, and reset their stats to what a fresh player would have.

 

  • Liked by
Reply
Cancel
1 on November 21, 2018

ill leave the code below, but shouldn’t the new weapon be exactly the same prefab?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Weapon : MonoBehaviour {

public static Weapon instance;

public float fireRate = 0;
public int damage = 10;
public float fireDistance = 100;
public LayerMask whatToHit;

public int maxAmmo = 10;
public int curAmmo;
public float reloadTime = 1f;
private bool isReloading = false;

public Transform BulletTrailPrefab;
public Transform HitPrefab;
public Transform MuzzleFlashPrefab;
float timeToSpawnEffect = 0;
public float effectSpawnRate = 10;

//Handle camera shaking
public float camShakeAmount = 0.05f;
public float camShakeLength = 0.1f;
CameraShake camShake;

public string weaponShootSound = “DefaultShot”;

float timeToFire = 0;
float muzzleMinSize = 0.6f;
float muzzleMaxSize = 0.9f;
float muzzleTimer = 0.02f;
float trailTimer = 0.04f;
float particleLifetime = 1f;
Transform firePoint;

//Caching
AudioManager audioManager;

// Use this for initialization
void Awake () {

firePoint = transform.Find(“FirePoint”);
if (firePoint == null) {

Debug.LogError(“No FirePoint”);

}

if (instance == null) {

instance = this;

}
}

void Start() {

curAmmo = maxAmmo;

camShake = GameMaster.gm.GetComponent<CameraShake>();
if (camShake == null) {

Debug.LogError(“No CameraShake script found on GM object”);

}

audioManager = AudioManager.instance;
if (audioManager == null) {

Debug.LogError(“No audioManager found”);

}

}

void OnEnable() {

isReloading = false;

}

// Update is called once per frame
void Update () {

if (isReloading == true) {

return;

}

//Press R to reload (make sure to write stuff on top of this, return stops the function)

if (Input.GetKeyDown(KeyCode.R)) {

StartCoroutine(Reload());
return;
}

if (curAmmo <= 0) {

StartCoroutine(Reload());
return;
}

if (fireRate == 0) {

if (Input.GetButtonDown (“Fire1”)) {

Shoot();

}

}
else {

if (Input.GetButton (“Fire1”) && Time.time > timeToFire) {
timeToFire = Time.time + 1 / fireRate;
Shoot();

}

}

}

IEnumerator Reload() {
isReloading = true;
Debug.Log(“Reloading…”);

yield return new WaitForSeconds(reloadTime);

curAmmo = maxAmmo;
isReloading = false;
}

void Shoot() {

curAmmo–;
Vector2 mousePosition = new Vector2 (Camera.main.ScreenToWorldPoint (Input.mousePosition).x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y);
Vector2 firePointPosition = new Vector2 (firePoint.position.x, firePoint.position.y);
RaycastHit2D hit = Physics2D.Raycast (firePointPosition, mousePosition – firePointPosition, fireDistance, whatToHit);

Debug.DrawLine (firePointPosition, (mousePosition – firePointPosition) * 100, Color.cyan);
if (hit.collider != null) {

Debug.DrawLine(firePointPosition, hit.point, Color.red);
Enemy enemy = hit.collider.GetComponent<Enemy>();
if (enemy != null) {

enemy.DamageEnemy(damage);
//Debug.Log(“We hit ” + hit.collider.name + ” and did ” + damage + ” damage “);

}

}

if (Time.time >= timeToSpawnEffect) {

Vector3 hitPos;
Vector3 hitNormal;

if (hit.collider == null) {

hitPos = (mousePosition – firePointPosition) * 30;
hitNormal = new Vector3(9999, 9999, 9999);
}
else {

hitPos = hit.point;
hitNormal = hit.normal;
}

Effect(hitPos, hitNormal);
timeToSpawnEffect = Time.time + 1 / effectSpawnRate;

}

}

void Effect(Vector3 hitPos, Vector3 hitNormal) {

Transform trail = Instantiate (BulletTrailPrefab, firePoint.position, firePoint.rotation) as Transform;
LineRenderer lr = trail.GetComponent<LineRenderer>();

if (lr != null) {

lr.SetPosition(0, firePoint.position); //0 is for element 0
lr.SetPosition(1, hitPos); //1 is for element 1

}

Destroy(trail.gameObject, trailTimer);

if (hitNormal != new Vector3(9999, 9999, 9999)) {

Transform hitParticle = Instantiate(HitPrefab, hitPos, Quaternion.FromToRotation(Vector3.forward, hitNormal)) as Transform;
Destroy(hitParticle.gameObject, particleLifetime);

}

Transform clone = Instantiate (MuzzleFlashPrefab, firePoint.position, firePoint.rotation) as Transform;
clone.parent = firePoint;
float size = Random.Range (muzzleMinSize, muzzleMaxSize);
clone.localScale = new Vector3 (size, size, size);
Destroy (clone.gameObject, muzzleTimer);

//Shake the camera
camShake.Shake(camShakeAmount, camShakeLength);

//Play shoot sound
audioManager.PlaySound(weaponShootSound);
}

}

 

Wise
on November 23, 2018

On my phone so I’ll look at the code later.
However, that’s not how prefabs work.
Just because it’s the same prefab, doesn’t mean it’s the same object.

Think of it like this. A prefab is like a copy from a copy machine. And when you’re trying to check the ammo of one of those copy’s you’re only looking at that one copy. If you destroy that copy, you’re still trying to look at that specific one, even if you may have printed 1000 of them. You need to tell it that you’re done looking at this one, and now look at this new one instead.

Show more replies
  • Liked by
Reply
Cancel
4 on November 24, 2018

hmm I thought since the prefab script has the same script inside it would just carry on, guess I’m mistaken, what would you recommend here?

Wise
on November 24, 2018

You can easily adjust what you have now with 1 line of code. Instead of making pistol a variable and only setting it once in the UI’s script, make it a better that just returns the instance EVERYTIME you access. Then it should just work.

However quick pro-tip: things like weapons shouldn’t be singletons. Only things that there can only absolutely ever be only one of should be. Things like entity and level managers.

on November 25, 2018

making a better? I’m sorry, I’m not sure I’m following, I’m quite new to this so excuse my ignorance, how would I let it know i wanted it to return every time it is accessed?

How would I make a weapon without being a child? like make it spawn and despawn every time it is changed?

Wise
on November 25, 2018

Getter. Sorry, still on phone.

on November 26, 2018

Okay, thank you for your help, it has been invaluable.

Show more replies
  • Liked by
Reply
Cancel