0

I am trying to instantiate a prefab. He is also located in my resources folder. However, I get an error saying "the object I want to instantiate is null".

I need help for fix this error ? Thanks

ArgumentException: The Object you want to instantiate is null.
UnityEngine.Object.CheckNullArgument (System.Object arg, System.String message) (at /Users/bokken/buildslave/unity/build/Runtime/Export/Scripting/UnityEngineObject.bindings.cs:374)
UnityEngine.Object.Instantiate (UnityEngine.Object original, UnityEngine.Vector3 position, UnityEngine.Quaternion rotation) (at /Users/bokken/buildslave/unity/build/Runtime/Export/Scripting/UnityEngineObject.bindings.cs:197)
UnityEngine.Object.Instantiate[T] (T original, UnityEngine.Vector3 position, UnityEngine.Quaternion rotation) (at /Users/bokken/buildslave/unity/build/Runtime/Export/Scripting/UnityEngineObject.bindings.cs:276)
CloneRedTarget.Duplicate () (at Assets/UI/Script/CloneRedTarget.cs:44)
---------
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class CloneRedTarget : MonoBehaviour
{
    public static int score = 0;
    public Text scoreText;
    public static GameObject targetGO;
    public GameObject winImage;
    public AudioSource shooterAudio;
    
    // Start is called before the first frame update
    void Start()
    {
        InvokeRepeating("Duplicate", 1f, 1f);
    }

    // Update is called once per frame
    void Update()
    {
        if (Target.win == true)
        {
            CancelInvoke("Duplicate");
            winImage.SetActive(true);

        }

        scoreText.text = score.ToString();

        if (Input.GetMouseButtonDown(0))
        {
            shooterAudio.Play();
        }
    }


    public void Duplicate()
    {
        float xp = Random.Range(-8f,8f);
        float yp = Random.Range(-2f, 4.2f);
        Vector3 rp = new Vector3(xp, yp, 0);
        Instantiate(targetGO, rp, Quaternion.identity);
    }
}

Scott Chamberlain
  • 116,967
  • 28
  • 260
  • 389

1 Answers1

0

It looks like you didn't reference the "targetGO" gameobject. Make sure you put the Prefab in the inspector window of the script so it can instantiate it (as shown below).

Sample

  • The "targetGO" gameobject, is a Prefab in the inspector window of the script. See the link https://i.stack.imgur.com/8rz7B.png – Fay_Dev_2020 Mar 16 '21 at 21:42
  • targetGO marked as static how did you assign it in editor? Thats the source of error. Normally you shouldnt be able to see it in editor also you cant see score value but can see the prefab field. Remove static and problem solved. – SeLeCtRa Mar 16 '21 at 23:22