Home > OS >  Can' instantiate a prefab in a certain time
Can' instantiate a prefab in a certain time

Time:06-24

I'm trying to instantiate a prefab in a certain time, but that gives me an error: "object reference not set to an instance of an object".

This is the code:

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

public class animatronicsManager : MonoBehaviour
{
    clockTime clockTime;
    public GameObject enemy;


    void Start()
    {
        clockTime.FindObjectOfType<clockTime>();
    }


    void Update()
    {
        if (clockTime.time2 == 10)
        {
            Instantiate(enemy, new Vector3(3.66f, -1, 0.66f), Quaternion.Euler(0, -190, 0));
        }
    }
}

i also tryed to to spawn it by pressing a key, and it works. Can you help me resolve this?

("time2" is an int variable that count time)

Thank you

CodePudding user response:

clockTime variable is never initialized in your code. This is the reason of the error. Initialize it in in your Awake() (or anywhere before trying to access in the Update() method)

CodePudding user response:

I suppose you wanted your Start to be like this

void Start()
{
    clockTime = FindObjectOfType<clockTime>();
}
  • Related