CanvasGroup issue

Hi guys im getting this error in my game when i try to pick items in my inventory to move them like shows the pick bellow.

the question is, why im getting this error if has u can see in scrip i define :

private CanvasGroup canvasGroup;

void Start
{
canvasGroup = getcomponent();
}

and then this error its in line 357 when i define the if statement???

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System;

public class Inventory : MonoBehaviour
{
    private RectTransform inventoryRect;

    private float inventoryWidth, inventoryHeight;

    public int slots;

    public int rows;

    public float slotPaddingLeft;

    public float slotPaddingTop;

    public float slotSize;

    private List<GameObject> allSlots;

    private float hoverYOffset;

    private CanvasGroup canvasGroup;

    private bool fadingIn;

    private bool fadingOut;

    public float fadeTime;

    private static int emptySlots;

    public static int EmptySlots
    {
        get{ return emptySlots; }
        set{ emptySlots = value; }
    }



    void Awake()
    {
        canvasGroup = GetComponent<CanvasGroup>();
    }

    void Start ()
    {

        CreateLayout();
    }



    void Update ()
    {
        if (Input.GetMouseButtonUp (0))
        {
            //Removes the selected item from the inventory
            if(!InventoryManager.Instance.eventSystem.IsPointerOverGameObject(-1) && InventoryManager.Instance.From != null)
            {
                InventoryManager.Instance.From.GetComponent<Image>().color = Color.white;

                InventoryManager.Instance.From.ClearSlot();

                Destroy (GameObject.Find ("Hover"));

                InventoryManager.Instance.To = null;

                InventoryManager.Instance.From = null;

                emptySlots++;
            }
        }

        if (InventoryManager.Instance.HoverObject != null)
        {
            Vector2 position;

            RectTransformUtility.ScreenPointToLocalPointInRectangle(InventoryManager.Instance.canvas.transform as RectTransform, Input.mousePosition, InventoryManager.Instance.canvas.worldCamera, out position);

            position.Set(position.x, position.y - hoverYOffset);

            InventoryManager.Instance.HoverObject.transform.position = InventoryManager.Instance.canvas.transform.TransformPoint(position);
        }

        if (Input.GetMouseButton (2))
        {
            if(InventoryManager.Instance.eventSystem.IsPointerOverGameObject(-1))
            {
                MoveInventory();
            }
        }
    }

    public void Open()
    {
        if(canvasGroup.alpha > 0)
        {
            StartCoroutine("FadeOut");
               
            PutItemBack();
        }
        else
        {
            StartCoroutine("FadeIn");
        }

    }



    public void ShowToolTip(GameObject slot)
    {
        Slot tmpslot = slot.GetComponent<Slot>();

        if (!tmpslot.IsEmpty && InventoryManager.Instance.HoverObject == null)
        {
            InventoryManager.Instance.visualTextObject.text = tmpslot.CurrentItem.GetToolTip();

            InventoryManager.Instance.sizeTextObject.text = InventoryManager.Instance.visualTextObject.text;


            InventoryManager.Instance.tooltipObject.SetActive(true);


            float xPos = slot.transform.position.x + slotPaddingLeft;

            float yPos = slot.transform.position.y - slot.GetComponent<RectTransform>().sizeDelta.y - slotPaddingTop;

            InventoryManager.Instance.tooltipObject.transform.position = new Vector2(xPos, yPos);
        }

    }



    public void HideToolTip()
    {
        InventoryManager.Instance.tooltipObject.SetActive(false);
    }



    public void SaveInventory()
    {
        string content = string.Empty;

        for (int i = 0; i < allSlots.Count; i++)
        {
            Slot tmp = allSlots[i].GetComponent<Slot>();

            if(!tmp.IsEmpty)
            {
                content += i + "-" + tmp.CurrentItem.type.ToString() + "-" + tmp.Items.Count.ToString() + ";";
            }
        }

        PlayerPrefs.SetString ("content", content);

        PlayerPrefs.SetInt ("slots", slots);

        PlayerPrefs.SetInt ("rows", rows);

        PlayerPrefs.SetFloat ("slotPaddingLeft", slotPaddingLeft);

        PlayerPrefs.SetFloat ("slotPaddingTop", slotPaddingTop);

        PlayerPrefs.SetFloat ("slotSize", slotSize);

        PlayerPrefs.SetFloat ("xPos", inventoryRect.position.x);

        PlayerPrefs.SetFloat ("yPos", inventoryRect.position.y);

        PlayerPrefs.Save();
    }



    public void LoadInventory()
    {
        string content = PlayerPrefs.GetString ("content");

        slots = PlayerPrefs.GetInt ("slots");

        rows = PlayerPrefs.GetInt ("rows");

        slotPaddingLeft = PlayerPrefs.GetFloat ("slotPaddingLeft");

        slotPaddingTop = PlayerPrefs.GetFloat ("slotPaddingTop");

        slotSize = PlayerPrefs.GetFloat ("slotSize");

        inventoryRect.position = new Vector3 (PlayerPrefs.GetFloat ("xPos"), PlayerPrefs.GetFloat ("yPos"), inventoryRect.position.z);

        CreateLayout();

        string[] splitContent = content.Split (';');    //0-MANA-3

        for (int x = 0; x < splitContent.Length-1; x++)
        {
            string[] splitValues = splitContent[x].Split('-');

            int index = Int32.Parse(splitValues[0]);    //"0"

            ItemType type = (ItemType)Enum.Parse(typeof(ItemType), splitValues[1]);    //"MANA"

            int amount = Int32.Parse(splitValues[2]);    //"3"

            //replace the item in inventory has many times has we have before
            for(int i = 0; i < amount; i++)
            {
                switch (type)
                {
                    case ItemType.MANA:
                        allSlots[index].GetComponent<Slot>().AddItem(InventoryManager.Instance.mana.GetComponent<Item>());
                        break;
                    case ItemType.HEALTH:
                        allSlots[index].GetComponent<Slot>().AddItem(InventoryManager.Instance.health.GetComponent<Item>());
                        break;
                    case ItemType.WEAPON:
                        allSlots[index].GetComponent<Slot>().AddItem(InventoryManager.Instance.weapon.GetComponent<Item>());
                        break;
                }
            }
        }
    }



    private void CreateLayout()
    {
        if(allSlots != null)
        {
            foreach(GameObject go in allSlots)
            {
                Destroy(go);
            }
        }

        allSlots = new List<GameObject>();

        hoverYOffset = slotSize * 0.01f;

        emptySlots = slots;

        inventoryWidth = (slots/rows) * (slotSize + slotPaddingLeft) + slotPaddingLeft;
        inventoryHeight = rows * (slotSize + slotPaddingTop) + slotPaddingTop;

        inventoryRect = GetComponent<RectTransform>();

        inventoryRect.SetSizeWithCurrentAnchors (RectTransform.Axis.Horizontal, inventoryWidth);
        inventoryRect.SetSizeWithCurrentAnchors (RectTransform.Axis.Vertical, inventoryHeight);
   
        int columns = slots / rows;

        for (int y = 0; y < rows; y++)
        {
            for(int x = 0; x < columns; x++)
            {
                GameObject newSlot = (GameObject)Instantiate(InventoryManager.Instance.slotPrefab);

                RectTransform slotRect = newSlot.GetComponent<RectTransform>();

                newSlot.name = "Slot";

                //set slot as parent of inventory, who is parent from canvas that draw sprites
                newSlot.transform.SetParent(this.transform.parent);

                slotRect.localPosition = inventoryRect.localPosition + new Vector3(slotPaddingLeft * (x + 1) + (slotSize * x), -slotPaddingTop * (y + 1) - (slotSize * y));

                slotRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, slotSize * InventoryManager.Instance.canvas.scaleFactor);   

                slotRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, slotSize * InventoryManager.Instance.canvas.scaleFactor);       

                newSlot.transform.SetParent(this.transform);

                allSlots.Add (newSlot);
            }
        }
    }



    public bool AddItem(Item item)
    {
        if (item.maxSize == 1)
        {
            PlaceEmpty(item);
            return true;
        }
        else
        {
            foreach (GameObject slot in allSlots)
            {
                Slot tmp = slot.GetComponent<Slot>();

                if(!tmp.IsEmpty)
                {
                    if(tmp.CurrentItem.type == item.type && tmp.IsAvailable)
                    {
                        tmp.AddItem(item);
                        return true;
                    }
                }
            }
            if(emptySlots > 0)
            {
                PlaceEmpty(item);
            }
        }

        return false;
    }



    private void MoveInventory()
    {
        Vector2 mousePos;

        RectTransformUtility.ScreenPointToLocalPointInRectangle (InventoryManager.Instance.canvas.transform as RectTransform, new Vector3 (Input.mousePosition.x - (inventoryRect.sizeDelta.x / 2 * InventoryManager.Instance.canvas.scaleFactor), Input.mousePosition.y + (inventoryRect.sizeDelta.y / 2 * InventoryManager.Instance.canvas.scaleFactor)), InventoryManager.Instance.canvas.worldCamera, out mousePos);

        transform.position = InventoryManager.Instance.canvas.transform.TransformPoint (mousePos);
    }



    private bool PlaceEmpty(Item item)
    {
        if (emptySlots > 0)
        {
            foreach (GameObject slot in allSlots)
            {
                Slot tmp = slot.GetComponent<Slot>();

                if(tmp.IsEmpty)
                {
                    tmp.AddItem(item);
                    emptySlots --;
                    return true;
                }
            }
        }

        return false;
    }



    public void MoveItem(GameObject clicked)
    {
        if (InventoryManager.Instance.From == null && canvasGroup.alpha == 1)
        {
            if (!clicked.GetComponent<Slot>().IsEmpty)
            {
                InventoryManager.Instance.From = clicked.GetComponent<Slot>();

                InventoryManager.Instance.From.GetComponent<Image>().color = Color.gray;


                InventoryManager.Instance.HoverObject = (GameObject)Instantiate(InventoryManager.Instance.iconPrefab);

                InventoryManager.Instance.HoverObject.GetComponent<Image>().sprite = clicked.GetComponent<Image>().sprite;

                InventoryManager.Instance.HoverObject.name = "Hover";


                RectTransform hoverTransform = InventoryManager.Instance.HoverObject.GetComponent<RectTransform>();

                RectTransform clickedTransform = clicked.GetComponent<RectTransform>();


                hoverTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, clickedTransform.sizeDelta.x);

                hoverTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, clickedTransform.sizeDelta.y);


                InventoryManager.Instance.HoverObject.transform.SetParent(GameObject.Find ("Canvas").transform, true);

                InventoryManager.Instance.HoverObject.transform.localScale = InventoryManager.Instance.From.gameObject.transform.localScale;
            }
        }
        else if (InventoryManager.Instance.To == null)
        {
            InventoryManager.Instance.To = clicked.GetComponent<Slot>();

            Destroy(GameObject.Find ("Hover"));
        }
        if (InventoryManager.Instance.To != null && InventoryManager.Instance.From != null)
        {
            Stack<Item> tmpTo = new Stack<Item>(InventoryManager.Instance.To.Items);

            InventoryManager.Instance.To.AddItems(InventoryManager.Instance.From.Items);

            if(tmpTo.Count == 0)
            {
                InventoryManager.Instance.From.ClearSlot();
            }
            else
            {
                InventoryManager.Instance.From.AddItems(tmpTo);
            }

            InventoryManager.Instance.From.GetComponent<Image>().color = Color.white;

            //reset "to" and "from"
            InventoryManager.Instance.To = null;

            InventoryManager.Instance.From = null;

            Destroy(GameObject.Find ("Hover"));
        }
    }



    private void PutItemBack()
    {
        if (InventoryManager.Instance.From != null)
        {
            Destroy(GameObject.Find("Hover"));

            InventoryManager.Instance.From.GetComponent<Image>().color = Color.white;

            InventoryManager.Instance.From = null;
        }
    }



    private IEnumerator FadeOut()
    {
        if (!fadingOut)
        {
            fadingOut = true;

            fadingIn = false;

            StopCoroutine("FadeIn");


            float startAlpha = canvasGroup.alpha;

            float rate = 1.0f / fadeTime;

            float progress = 0.0f;


            while(progress < 1.0)
            {
                canvasGroup.alpha = Mathf.Lerp(startAlpha, 0, progress);

                progress += rate * Time.deltaTime;

                yield return null;
            }

            canvasGroup.alpha = 0;

            fadingOut = false;
        }
    }



    private IEnumerator FadeIn()
    {
        if (!fadingIn)
        {
            fadingOut = false;
           
            fadingIn = true;
           
            StopCoroutine("FadeOut");
           
           
            float startAlpha = canvasGroup.alpha;
           
            float rate = 1.0f / fadeTime;
           
            float progress = 0.0f;
           
           
            while(progress < 1.0)
            {
                canvasGroup.alpha = Mathf.Lerp(startAlpha, 1, progress);
               
                progress += rate * Time.deltaTime;
               
                yield return null;
            }
           
            canvasGroup.alpha = 1;
           
            fadingIn = false;
        }
    }
}

!Bump

Hello,

Your CanvasGroup needs to be attached to the canvas and not the inventory

:wink:

1 Like

its already fixed but ty anyway m8

1 Like