Noticias

¡RECUERDA QUE SI ERES UN NUEVO USUARIO, DEBES PRESENTARTE PARA PODER PUBLICAR MENSAJES! | TENEMOS CANAL OFICIAL DE TELEGRAM: t.me/unity3dspain

Null Reference Exception

Iniciado por Siam, Diciembre 22, 2016, 06:00:55 PM

Tema anterior - Siguiente tema
Buenos días.
 
Estoy intentando agregar un item al inventario al tocarlo desde la pantalla de juego. Al tocar el item me da un Null Reference Exception.
 
El player tiene este script.
 

public Transform localDrop;
public inventario inv;
void Start ()
{
   inv =(inventario) FindObjectOfType (typeof(inventario));
}

//soltar items, funciona bien
public void DropItems(Items item)
{
   GameObject tmpDrop = (GameObject)Instantiate (item.itemDrop, localDrop.position, Quaternion.identity);
   Collectable tmpClt = tmpDrop.GetComponent<Collectable> ();
   tmpClt.nameItem = item.names;
}

void OnCollisionEnter2D(Collision2D collision)
{
   if (collision.gameObject.tag == "Item")
   {
      Collectable cole = collision.gameObject.GetComponent<Collectable> ();
      inv.AddItems (cole.nameItem, -1);
      Destroy (collision.gameObject);
   }
}

 
El error da en inv.AddItems (cole.nameItem, -1)
 



   
      NullReferenceException: Object reference not set to an instance of an object

      playerCollectable.OnCollisionEnter2D (UnityEngine.Collision2D collision) (at Assets/Scripts/playerCollectable.cs:38)
   

[/quote]
 
Este es la funcion de AddItems de inventario. Esta funcion se usa tambien al abrir el inventario para cargar los items que ya tenias previamente y es ese caso funciona perfectamente
 

public class inventario : MonoBehaviour {
public List <Items> inventary = new List<Items>();
    private DataBase db;
     
     
     void Start ()
{
   contChild = transform.childCount;
   db =(DataBase) FindObjectOfType (typeof(DataBase));
    }
     
      public void AddItems(string name, int numSlot)
{
   if (numSlot != -1)
   {
      for (int i = 0; i < inventary.Count; i++)
      {
         //si el slot esta vacio/disponible busca en la bbdd el item y lo agrega al inventario
         if (inventary .names == null)
         {
            for (int j = 0; j < db.item.Count; j++)
            {
               if (db.item [j].names == name && i == numSlot)
               {
                  inventary = db.item [j];
               }
            }
         }
      }
   }
   else
   {
      for (int i = 4; i < inventary.Count; i++)
      {
         if (inventary .names == null)
         {
            for (int j = 0; j < db.item.Count; j++)
            {
               if (db.item [j].names == name)
               {
                  inventary = db.item [j];
               }
            }
         }
      }
   }
}

 
Y el item que se puede recoger tiene la clase Collectable
 

public class Collectable : MonoBehaviour
{
public string nameItem;
public int amount;
}

 
No entiendo el Null si tanto inv como cole si estan instanciados.
 
No se si tendra algo que ver pero el inventario esta creado en otra escena el cual cargo/descargo al dar a una tecla.

Si la Variable "inv" está sien
 


void OnCollisionEnter2D(Collision2D collision)
{
   if (collision.gameObject.tag == "Item")
   {
      Collectable cole = collision.gameObject.GetComponent<Collectable> ();
              if(cole != null)
              {
            inv.AddItems (cole.nameItem, -1);
            Destroy (collision.gameObject);
              }
              else
              {
                    Debug.Log("erro el item no contiene el componente Collectable");
              }
   }
}

 
do correctamente asignada el problema se debe a que no esta tomando el componente la función GetComponent.

Diciembre 22, 2016, 07:27:14 PM #2 Ultima modificación: Diciembre 22, 2016, 07:51:27 PM por Siam
Vale ya esta, el fallo es que en el start cargaba el inventario, pero hasta que no pulso la I para abrir el inventario no existe iinventario

Etiquetas: