Page 1 sur 3

Inventaire UI Vie Objets

Publié : 28 Jan 2017 11:46
par emma43210
Bonjour, je suis nouvelle sur le site. Je m'appelle Emma, et j'ai un mini projet simplement pour comprendre le fonctionnement d'un inventaire (pour me faire la main avec les UI :-D ).

Alors j'ai un inventaire à peux près fonctionnel, mais je m'arrache les cheveux sur un problème. Celui ci est... Mettre de la vie sur une arme. Je m'explique :p

Alors je mets une arme sur un slot spécial. J'utilise cette arme, à chaque coup, elle perd de la vie. Lorsque je suis à 0, je veux supprimer cette arme de l'inventaire (Donc supprimer l'icone "Arme" dans le slot) Et c'est la ou je rencontre un soucis.... :triste1:

voici le script :

Code : Tout sélectionner


using UnityEngine;

public class WeaponController : MonoBehaviour
{
    public GameObject weaponHand;
    private ItemWeapon weapon;
    private Animator animator;
	public GameObject weaponModel;

	public bool StaffWhiteIsEquip = false;
	public bool StaffGreenIsEquip = false;

	public int healthStaffBlue = 5;

	void Start ()
	{
	
	}

    void Awake()
    {
        animator = GetComponent<Animator>();
    }

    void Update()
    {
        if (GameController.Instance.GameState != GameStates.Game) return;
        animator.SetBool("IsAttack", InputController.Weapon);

		if (weapon == null)
		{
			StaffWhiteIsEquip = false;
			StaffGreenIsEquip = false;
		}
		else
		{
//			StaffWhiteIsEquip = true;
//			StaffGreenIsEquip = true;
		}
    }

    // by the animation event
    public void OnAttack()
    {
        if (weapon == null) return;
        PlayerController player = PlayerController.Instance;
        if (weapon.itemType == Item.ItemTypes.Staff)
        {
            ItemWeaponStaff staff = (ItemWeaponStaff)weapon;
			if (player.Mana >= staff.mana && healthStaffBlue > 0)
            {
                Instantiate(staff.bullet, player.mainCamera.transform.position, player.mainCamera.transform.rotation);
                player.Mana -= staff.mana;

				//Pour supprimer staffBlue (Arme) quand elle n'a plus de vie 
				if (weapon.model.name == "StaffBlue") 
				{
					healthStaffBlue--;

					if (healthStaffBlue <= 0)
						//Destroy (weaponModel);
						//weapon = null;
				}

				
            }
            else
            {
                UIController.Instance.ShowError("Not enought mana");
            }
        }
        else
        {
            RaycastHit hit;
            if (Physics.Raycast(player.mainCamera.transform.position, player.mainCamera.transform.TransformDirection(Vector3.forward), out hit, 4))
            {
                IHitable hitable = hit.collider.gameObject.GetComponent(typeof(IHitable)) as IHitable;
                if (hitable != null)
                {
                    DamageConfig damageWithStreanght = ((ItemWeaponMelee)weapon).damage.Copy();
                    damageWithStreanght.minPhysical += (int)(damageWithStreanght.minPhysical * 0.05f * PlayerController.Instance.experience.ActualStrenght);
                    damageWithStreanght.maxPhysical += (int)(damageWithStreanght.maxPhysical * 0.05f * PlayerController.Instance.experience.ActualStrenght);
                    hitable.Hit(new HitInfo(damageWithStreanght, hit.point, true, HitInfo.HitSources.Player));
                }
            }
        }
    }

    public void OnSetWeapon(ItemWeapon weapon)
    {
        this.weapon = weapon;
        animator.SetBool("IsAttack", false);
		if (weaponModel != null) Destroy(weaponModel);
        if (weapon == null)
        {
            animator.SetInteger("WeaponType", -1);
        }
        else
        {
            weaponModel = (GameObject)Instantiate(weapon.model);
			weaponModel.transform.parent = weaponHand.transform;
			weaponModel.transform.localPosition = Vector3.zero;
            weaponModel.transform.localRotation = Quaternion.identity;
            //weaponModel.transform.localScale = Vector3.one;
            animator.SetInteger("WeaponType", ItemWeapon.GetAnimationId(weapon));
        }

		if (weapon.model.name == "StaffWhite")// if WeaponModel == StaffWhite 
		{
			StaffWhiteIsEquip = true;
		}
		else if (weapon.model.name != "StaffWhite")// if WeaponModel == StaffWhite 
		{
			StaffWhiteIsEquip = false;
		}

		if (weapon.model.name == "StaffGreen")// if WeaponModel == StaffGreen 
		{
			StaffGreenIsEquip = true;
		}
		else if (weapon.model.name != "StaffGreen" )// if WeaponModel == StaffGreen 
		{
			StaffGreenIsEquip = false; 
		}
    }
}



Je tiens à dire que j'ai regardé 2-3 tutos pour m'aiguiller dans la réalisation de cet inventaire et que le code risque de faire crier quelques personne """très rigoureuse""" je vous pries donc de m'excuser :p

Re: Inventaire UI Vie Objets

Publié : 28 Jan 2017 13:04
par Moi 1971
Bonjour,
Pourrais-tu te présenter dans la section adéquate?

Dans ton code ;

Code : Tout sélectionner

 //Pour supprimer staffBlue (Arme) quand elle n'a plus de vie
            if (weapon.model.name == "StaffBlue")
            {
               healthStaffBlue--;

               if (healthStaffBlue <= 0)
                  //Destroy (weaponModel);
                  //weapon = null;
            }
Pourquoi "weapon = null;" est mis en commentaire? Qu'en est-il dans les tutos que tu as suivi?

Re: Inventaire UI Vie Objets

Publié : 28 Jan 2017 13:29
par emma43210
Merci pour ta réponse ! ;-)

Dans la section adéquate ? Je n'ai pas l'habitude des forums.. :|

Alors Weapon = null en commentaire c'est pour (essayer) de ne plus instantier des projectiles avec l'armes (Comment ca uand je tire, rien ne ce passe :p)

Les tutos que j'ai suivies, c'était simplement des tutos "basiques" qui expliquaient brièvement comment réaliser un inventaire (Ils étaient en Anglais donc un peux dur à suivre) :)

Re: Inventaire UI Vie Objets

Publié : 28 Jan 2017 14:16
par Max
emma43210 a écrit :Dans la section adéquate ? Je n'ai pas l'habitude des forums.. :|
Dans la section 'Présentation', tout simplement.
emma43210 a écrit :Les tutos que j'ai suivies, c'était simplement des tutos "basiques" qui expliquaient brièvement comment réaliser un inventaire (Ils étaient en Anglais donc un peux dur à suivre) :)
Les Liens vers ces tuto serait intéressant. :mrgreen:

Re: Inventaire UI Vie Objets

Publié : 28 Jan 2017 14:17
par Moi 1971
Pour se présenter : dans la partie "Communauté" dans la sous section "Présentation des membres".
Tu peux regarder comment les autres ont fait pour t'en inspirer ou tu fais comme tu veux ;-)
Sinon, pour ton code, c'est bien trop compliqué dans son ensemble pour pouvoir comprendre le fonctionne de la petite partie que tu nous as communiquée. :(

Re: Inventaire UI Vie Objets

Publié : 28 Jan 2017 14:22
par Moi 1971
De plus,
- Toute ta série de if(true) else if (false) est inutile.
- A chaque attaque tu fais => "PlayerController player = PlayerController.Instance;" ???!!...
- tu crées des weaponModel puis tu les détruits les uns derrière les autres.?!?...

Re: Inventaire UI Vie Objets

Publié : 28 Jan 2017 15:08
par emma43210
Très bien je file me présenter alors :p

Les liens vers les tutos je ne les ais plus désolé... ça remonte a quelques mois et je ne ma rappelle plus du tout de leurs nom...

ceci :

Code : Tout sélectionner

 if (weapon.model.name == "StaffWhite")// if WeaponModel == StaffWhite 
      {
         StaffWhiteIsEquip = true;
      }
      else if (weapon.model.name != "StaffWhite")// if WeaponModel == StaffWhite 
      {
         StaffWhiteIsEquip = false;
      }

      if (weapon.model.name == "StaffGreen")// if WeaponModel == StaffGreen 
      {
         StaffGreenIsEquip = true;
      }
      else if (weapon.model.name != "StaffGreen" )// if WeaponModel == StaffGreen 
      {
         StaffGreenIsEquip = false; 
      }
    }
c'est juste des Test à ne pas tenir compte je peux les supprimer ^^



pour ça : PlayerController player = PlayerController.Instance; ça fesais partie du tuto et je n'aie pas réussie à comprendre à quoi cela servait...

Re: Inventaire UI Vie Objets

Publié : 28 Jan 2017 17:09
par emma43210
Est ce que parmis vous il y a quelqu'un qui arriverais à comprendre ce script ? :p

Code : Tout sélectionner


using UnityEngine;
using UnityEngine.UI;

public class InventoryScreen : Form
{
    public ItemSlot[] slots;
    public ItemSlot weaponSlot;
    public ItemSlot armorSlot;
    public ItemSlot helmetSlot;
    public ItemSlot amuletSlot;
    public ItemSlot ringSlot;
    public ItemSlot dropSlot;

    public Text levelText;
    public Text pointsText;

    public Slider strenghtSlider;
    public Slider staminaSlider;
    public Slider mindSlider;
    public Slider willpowerSlider;

    public Text strenghtText;
    public Text staminaText;
    public Text mindText;
    public Text willpowerText;

    public Button addStrenghtButton;
    public Button addStaminaButton;
    public Button addMindButton;
    public Button addWillpowerButton;

    public Text protectionPhysicalText;
    public Text protectionFireText;
    public Text protectionIceText;
    public Text protectionElectroText;

    public Text hintText;
    public Image dragIcon;
    public Color defaultTextColor = Color.grey;
    public Color highlightTextColor = Color.green;

    private ItemSlot hoveredSlot;

	WeaponController weaponControl;
	Item item;
	public GameObject StaffWhite;
	public Transform PlayerHand;

    void Start()
    {
        strenghtSlider.maxValue = ExperienceController.maxSkillLevel;
        staminaSlider.maxValue = ExperienceController.maxSkillLevel;
        mindSlider.maxValue = ExperienceController.maxSkillLevel;
        willpowerSlider.maxValue = ExperienceController.maxSkillLevel;
        addStrenghtButton.onClick.AddListener(OnAddStrenghtClick);
        addStaminaButton.onClick.AddListener(OnAddStaminaClick);
        addMindButton.onClick.AddListener(OnAddMindClick);
        addWillpowerButton.onClick.AddListener(OnAddWillpowerClick);
        hintText.text = "";

        weaponSlot.onDblClick += OnSlotDblClick;
        armorSlot.onDblClick += OnSlotDblClick;
        helmetSlot.onDblClick += OnSlotDblClick;
        amuletSlot.onDblClick += OnSlotDblClick;
        ringSlot.onDblClick += OnSlotDblClick;

        weaponSlot.onHover += OnSlotHover;
        armorSlot.onHover += OnSlotHover;
        helmetSlot.onHover += OnSlotHover;
        amuletSlot.onHover += OnSlotHover;
        ringSlot.onHover += OnSlotHover;
        dropSlot.onHover += OnSlotHover;

        foreach (ItemSlot itemSlot in slots)
        {
            itemSlot.onDblClick += OnSlotDblClick;
            itemSlot.onHover += OnSlotHover;
            itemSlot.onDrag += OnSlotDrag;
        }
        foreach (ItemSlot itemSlot in UIController.Instance.gameScreen.slots)
        {
            itemSlot.onDblClick += OnSlotDblClick;
            itemSlot.onHover += OnSlotHover;
            itemSlot.onDrag += OnSlotDrag;
        }
    }

	void Update()
    {
        if (IsShown == false) return;
        PlayerController player = PlayerController.Instance;

        levelText.text = "Level: " + player.experience.Level;
        pointsText.text = "Points: " + player.experience.Points;

        Vector2 localPoint;
        RectTransformUtility.ScreenPointToLocalPointInRectangle(rootPanel.GetComponent<RectTransform>(), Input.mousePosition, null, out localPoint);
        if (dragIcon.gameObject.activeSelf == true)
        {
            dragIcon.transform.parent.GetComponent<RectTransform>().anchoredPosition = localPoint;
        }

        strenghtSlider.value = player.experience.Strenght;
        staminaSlider.value = player.experience.Stamina;
        mindSlider.value = player.experience.Mind;
        willpowerSlider.value = player.experience.Willpower;

        strenghtText.text = player.experience.ActualStrenght.ToString();
        staminaText.text = player.experience.ActualStamina.ToString();
        mindText.text = player.experience.ActualMind.ToString();
        willpowerText.text = player.experience.ActualWillpower.ToString();
        strenghtText.color = player.experience.AdditionalStrenght > 0 ? highlightTextColor : defaultTextColor;
        staminaText.color = player.experience.AdditionalStamina > 0 ? highlightTextColor : defaultTextColor;
        mindText.color = player.experience.AdditionalMind > 0 ? highlightTextColor : defaultTextColor;
        willpowerText.color = player.experience.AdditionalWillpower > 0 ? highlightTextColor : defaultTextColor;

        addStrenghtButton.interactable = player.experience.Points > 0 && player.experience.Strenght < ExperienceController.maxSkillLevel;
        addStaminaButton.interactable = player.experience.Points > 0 && player.experience.Stamina < ExperienceController.maxSkillLevel;
        addMindButton.interactable = player.experience.Points > 0 && player.experience.Mind < ExperienceController.maxSkillLevel;
        addWillpowerButton.interactable = player.experience.Points > 0 && player.experience.Willpower < ExperienceController.maxSkillLevel;

        protectionPhysicalText.text = "Physical: " + (Mathf.RoundToInt(player.defence.physical * 100));
        protectionFireText.text = "Fire: " + (Mathf.RoundToInt(player.defence.fire * 100));
        protectionIceText.text = "Ice: " + (Mathf.RoundToInt(player.defence.ice * 100));
        protectionElectroText.text = "Electro: " + (Mathf.RoundToInt(player.defence.electro * 100));

        weaponSlot.SetItem(player.inventory.Weapon);
        armorSlot.SetItem(player.inventory.Armor);
        helmetSlot.SetItem(player.inventory.Helmet);
        amuletSlot.SetItem(player.inventory.Amulet);
        ringSlot.SetItem(player.inventory.Ring);
        foreach (ItemSlot slot in slots)
        {
            slot.SetItem(InventoryController.Instance.Items[slot.id]);
        }
    }

    public override void Show()
    {
        base.Show();
        hintText.text = "";
        dragIcon.gameObject.SetActive(false);
    }

    private void OnAddStrenghtClick()
    {
        PlayerController.Instance.experience.AddStrenght(1, false);
    }

    private void OnAddStaminaClick()
    {
        PlayerController.Instance.experience.AddStamina(1, false);
    }

    private void OnAddMindClick()
    {
        PlayerController.Instance.experience.AddMind(1, false);
    }

    private void OnAddWillpowerClick()
    {
        PlayerController.Instance.experience.AddWillpower(1, false);
    }

    private void OnSlotDblClick(ItemSlot slot)
    {
		if (slot == weaponSlot) { InventoryController.Instance.SetWeapon(null); return; }
		if (slot == armorSlot) { InventoryController.Instance.SetArmor(null); return; }
        if (slot == helmetSlot) { InventoryController.Instance.SetHelmet(null); return; }
        if (slot == amuletSlot) { InventoryController.Instance.SetAmulet(null); return; }
        if (slot == ringSlot) { InventoryController.Instance.SetRing(null); return; }
        InventoryController.Instance.UseItem(slot.id);
    }

    private void OnSlotHover(ItemSlot slot, bool state)
    {
        if (state == true)
        {
            hoveredSlot = slot;
            if (slot.ItemInSlot != null) hintText.text = slot.ItemInSlot.name + slot.ItemInSlot.description;
        }
        else
        {
            hoveredSlot = null;
            hintText.text = "";
        }
    }

    private void OnSlotDrag(ItemSlot slot, bool state)
    {
        if (state == true)
        {
            if (slot.ItemInSlot != null)
            {
                dragIcon.gameObject.SetActive(true);
                dragIcon.sprite = slot.ItemInSlot.icon;
				//Debug.Log ("Tu déplace un objet dans l'inventaire!"); // Okay
            }
        }
        else
        {
			if (slot.ItemInSlot != null && hoveredSlot != null)
            {
				if (hoveredSlot.slotType == ItemSlot.SlotTypes.Drop )
                {
                    InventoryController.Instance.Drop(slot.id);
					Debug.Log (slot.ItemInSlot.name); // Name of the object thrown (If I slip the icon of the object in a specific slot, I get the name of this object)
					//Instantiate objects in scene
					Instantiate (Resources.Load ("Objets/" + slot.ItemInSlot.name) as GameObject, PlayerHand.position, Quaternion.identity);
                }
                if (hoveredSlot.slotType == ItemSlot.SlotTypes.Backpack)
                {
                    InventoryController.Instance.Move(slot.id, hoveredSlot.id);
					//Debug.Log ("Objet posé dans une case de l'inventaire"); //fonctionne
                }
            }
            dragIcon.gameObject.SetActive(false);
        }
    }
}



Re: Inventaire UI Vie Objets

Publié : 28 Jan 2017 18:03
par Moi 1971
emma43210 a écrit :Est ce que parmis vous il y a quelqu'un qui arriverais à comprendre ce script ? :p
Le week-end il y a très peu de personne, il va te falloir attendre lundi matin pour avoir plus de monde.

Re: Inventaire UI Vie Objets

Publié : 28 Jan 2017 18:17
par emma43210
Pas de soucis :p