Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Instantiate returns as null, why?

Discussion in 'Scripting' started by AJones3D, Oct 23, 2019.

  1. AJones3D

    AJones3D

    Joined:
    Sep 25, 2019
    Posts:
    10
    I have a script shown below that instantiates a Prefab called "Arrow" in my project, but I keep getting the error "The object you want to instantiate is null." I referenced the Prefab, and typed it as GameObject. What am I missing?



    GameObject arrow;
    void Start()
    {
    arrow = Resources.Load("Arrow") as GameObject;
    }

    // Update is called once per frame
    void Update()
    {
    if(Input.GetMouseButtonDown(0))
    {
    GameObject Arrow = Instantiate(arrow) as GameObject;
    arrow.transform.position = transform.position + Camera.main.transform.forward * 2;
    Rigidbody arr = arrow.GetComponent<Rigidbody>();
    arr.velocity = Camera.main.transform.forward * 40;
    }
    }
    }
     
  2. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,832
    Please use code tags.

    Your title says Instantiate is returning null, but the error message you quote seems to say that arrow (the object you are trying to copy) is null. Probably something went wrong at the Resources.Load step.

    Also, the fact that you have separate variables called "arrow" and "Arrow" is probably a bad idea from a code readability standpoint.
     
    Joe-Censored likes this.
  3. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    Unrelated to your error, I'm sure you're making a mistake instantiating the object as "Arrow" but only trying to change the velocity and position of the "arrow" prefab instead.