Search Unity

Question Object reference not set to an instance of an object

Discussion in 'Scripting' started by KuHan1010, Aug 22, 2020.

  1. KuHan1010

    KuHan1010

    Joined:
    Aug 13, 2020
    Posts:
    2
    Code (CSharp):
    1. public class MotorCarretera : MonoBehaviour
    2. {
    3.     public GameObject motorCarretera;
    4.     public GameObject[] contenedorCalles;
    5.     public float speed;
    6.     public int selectorDeCalle;
    7.     public int contadorDeCalle = 0;
    8.    
    9.     // Start is called before the first frame update
    10.     void Start()
    11.     {
    12.         juegoTerminado = false;
    13.         creaCalle();
    14.     }
    15.  
    16.     // Update is called once per frame
    17.     void Update()
    18.     {
    19.         motorCarretera.transform.Translate(Vector3.down * speed * Time.deltaTime);
    20.     }
    21.  
    22.     public void creaCalle()
    23.     {
    24.         selectorDeCalle = Random.Range(0, 5);
    25.         GameObject Calle = (GameObject)Instantiate(contenedorCalles[selectorDeCalle],new Vector3(0,50,0),transform.rotation);
    26.         Calle.SetActive(true);
    27.         contadorDeCalle++;
    28.         Calle.name = "calle" + contadorDeCalle;
    29.         Calle.transform.parent = motorCarretera.transform;
    30.         GameObject piezaAux = GameObject.Find("calle" + (contadorDeCalle - 1));
    31.         Calle.transform.position = new Vector3(transform.position.x,
    32.                                                 piezaAux.GetComponent<Renderer>().bounds.size.y +
    33.                                                 piezaAux.transform.position.y,
    34.                                                 piezaAux.transform.position.z);
    35.  
    36.     }
    37.  
    38. }
    The error happen when i try to use Calle.transform.position, i don't know where is the error, i already instantiate it, it's still working but i am learning, so i want to know where is the error, thanks for your help
     
  2. adehm

    adehm

    Joined:
    May 3, 2017
    Posts:
    369
    The error code should say the line number. If you post the entire error someone will likely help you.
     
  3. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,911
    Most likely your GameObject.Find call is not finding anything. GameObject.Find is an error-prone and slow way of getting object references. I suggest using a different method.

    Anyway if you want to just solve your specific issue, use Debug.Log and print out what string you're trying to find, then compare that to the obejct names in your scene.