I have the following problem: I have a script in unity (C#) which establishes a connection with the database. It provides it alone, in a GameObject and it works without any problem for me by placing the method with the name Start , I can see the database records without any problem. The problem comes to me when I change the name of the method to Dbcontec and I try to call it in another script at the time of compiling, it generates an error. Below I leave the code of the scripts to see if they can help me.
Connection with the database.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Data;
using Mono.Data.Sqlite;
namespace Dbconection {
public class Dbcnx : MonoBehaviour {
public int Idrow;
// Use this for initialization
public void Dbcontec () {
string conn = "URI=file:" + Application.dataPath + "/db_cuentos.s3db"; //Path to database.
IDbConnection dbconn;
dbconn = (IDbConnection) new SqliteConnection(conn);
dbconn.Open(); //Open connection to the database.
IDbCommand dbcmd = dbconn.CreateCommand();
string sqlQuery = "SELECT * " + "FROM data_cuent Where id = '"+Idrow+"'";
dbcmd.CommandText = sqlQuery;
IDataReader reader = dbcmd.ExecuteReader();
while (reader.Read())
{
int id = reader.GetInt32(0);
string nombre = reader.GetString(1);
//int rand = reader.GetInt32(2);
Debug.Log( "id= "+id+" nombre ="+nombre);
}
reader.Close();
reader = null;
dbcmd.Dispose();
dbcmd = null;
dbconn.Close();
dbconn = null;
}
}
}
Script where I am calling the connection
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Dbconection;
public class Inicio : MonoBehaviour {
public Dbcnx dbcnx;
public int Idrow;
// Use this for initialization
void Start () {
dbcnx.Dbcontec();
}
}
Error that is generated.
NullReferenceException: Object reference not set to an instance of an object Start.Start () (at Assets/Start.cs:13)
You need to instantiate the class before calling the method: