2
votes

I'm using a namespace to instantiate a prefab in my game however unity thinks that the prefab is not a GameObject and returns the NullReferenceException error

I've linked the Prefab, properly in the GameObject that holds the script. This is the code that I currently have in Visual Studio but I also tried various forms of the code, they are what follows the first lines of code

public GameObject Prefab;
public void OnAppear(){
GameObject spawn = Instantiate(Prefab, Spawnpoint.position, Spawnpoint.rotation);
spawn.transform.parent = Spawnpoint.transform;}

V1 var spawn = Instantiate(Prefab, Spawnpoint.position, Spawnpoint.rotation);

V2 var spawn = Instantiate(Prefab, Spawnpoint.position, Spawnpoint.rotation) as GameObject;

Entire script:

namespace AugReal
{
    public class StartAll : MonoBehaviour
    {
        public Transform Spawnpoint;
        public GameObject Prefab;

        public void OnAppear()
        {
            GameObject spawn = Instantiate(Prefab, Spawnpoint.position, Spawnpoint.rotation);
            spawn.transform.parent = Spawnpoint.transform;
        }

        public void OnDisappear()
        {
            Debug.Log("You lose");
        }
    }
}

Inspector:

enter image description here

1
What do you mean by "namespace to instantiate a prefab"?Dimitar
Can you show where you are defining SpawnPoint? I suspect that is what is not defined.Erik Overflow
Maybe it's the Spawnpoint the error is telling you aboutMilos Romanic
As @ErikOverflow commented before, the problem seems to be the SpawnPoint object which may not be initialized. Are you linking any object to it in the Unity editor? (doesn't matter if it is a GameObject or Transform)Saeleas
Can you include a screenshot of the inspector for the object you have this code attached to?Draco18s no longer trusts SE

1 Answers

1
votes

Try the following code instead:

  1. You do not need to create a public reference to the transform that this script is attached to. Since the script is a monobehaviour, you can directly access this via this.transform
  2. Rather than setting the parent explicitly after instantiating, consider usign the Instantiate method with the parent override.

(I have also change the casing on your property "Prefab". It doesn't affect the code, but standard is to keep property names camelCase to distinguish them from the PascalCased class types.)

namespace AugReal
{
    public class StartAll : MonoBehaviour
    {
        public GameObject prefab;

        public void OnAppear()
        {
            GameObject spawn = Instantiate(prefab, this.transform);
        }

        public void OnDisappear()
        {
            Debug.Log("You lose");
        }
    }
}