Swap weapon button sprites for pressed state and normal states

posted in: Weekly Progress | 0

Icon controller script is added.

 

 

public class WeaponIconController : MonoBehaviour
{
public GameObject RopeButton;
public GameObject ShotgunButton;
public GameObject RifleButton;

private ButtonImageController _ropeBtnImgController;
private ButtonImageController _shotgunBtnImgController;
private ButtonImageController _rifleBtnImgController;

private Player.eEqippedWeapon _equippedWeapon;

public void Start()
{
_ropeBtnImgController = RopeButton.GetComponent<ButtonImageController>();
_shotgunBtnImgController = ShotgunButton.GetComponent<ButtonImageController>();
_rifleBtnImgController = RifleButton.GetComponent<ButtonImageController>();
_equippedWeapon = Player.eEqippedWeapon.Rope;
UpdateButtonsImages();
}

public void Update()
{
// change the sprites of weapons pressed/unpressed
// check if weapon is changed via keys
#if UNITY_EDITOR
_equippedWeapon = LevelManager.Instance.WeaponController.GetEquippedWeapon();
UpdateButtonsImages();
#endif
}

public void SelectWeapon(string weaponName)
{
// unpress all icons
if(weaponName == “Rope”)
{
_equippedWeapon = Player.eEqippedWeapon.Rope;
}
else if (weaponName == “Shotgun”)
{
_equippedWeapon = Player.eEqippedWeapon.Shotgun;
}
else if (weaponName == “Rifle”)
{
_equippedWeapon = Player.eEqippedWeapon.Rifle;
}

LevelManager.Instance.WeaponController.EquipWeapon(_equippedWeapon);
GameObject myEventSystem = GameObject.Find(“EventSystem”);
myEventSystem.GetComponent<UnityEngine.EventSystems.EventSystem>().SetSelectedGameObject(null);

UpdateButtonsImages();
}

private void ResetButtonsImages()
{
if(!_ropeBtnImgController || !_shotgunBtnImgController || !_rifleBtnImgController)
return;

_ropeBtnImgController.SetNormalSprite();
_shotgunBtnImgController.SetNormalSprite();
_rifleBtnImgController.SetNormalSprite();
}

private void UpdateButtonsImages()
{
ResetButtonsImages();
if (_equippedWeapon == Player.eEqippedWeapon.Rope)
{
_ropeBtnImgController.SetPressedSprite();
}
else if (_equippedWeapon == Player.eEqippedWeapon.Shotgun)
{
_shotgunBtnImgController.SetPressedSprite();
}
else if (_equippedWeapon == Player.eEqippedWeapon.Rifle)
{
_rifleBtnImgController.SetPressedSprite();
}
}
}

 

 

 

 

 

Pressed and normal state of button effect is added.

 

sing UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class ButtonImageController : MonoBehaviour
{
public Sprite NormalSprite;
public Sprite PressedSprite;
private Image _buttonImageRef;

public void Start()
{
_buttonImageRef = GetComponent<Image>();
}

public void SetNormalSprite()
{
_buttonImageRef.sprite = NormalSprite;
}
public void SetPressedSprite()
{
_buttonImageRef.sprite = PressedSprite;
}
}

Leave a Reply