Script not recognizing a prefab.

Hey Everyone,
I’m trying to create a script where it instantiates a prefab. I’m getting an error “The name does not exist in its current context”. Now, I literally have the same exact code as one of my other scripts, but I’m fairly new to Unity, so I am probably doing something obviously wrong somewhere. My code is below. I’m getting an error on Prefab1. I’ve tried dragging Prefab1 onto dd in the inspector, set it to None, and I still get that same error. Any help would be appreciated!

Thanks!

using UnityEngine;

using System.Collections;

public class FireButton : MonoBehaviour {

public GameObject dd;
// Use this for initialization
void Start () {
	dd = (GameObject)Instantiate(Prefab1);
}

2 Answers

2

I’m not savvy with C#, but first of all check that your filename is the same as your class name (i.e. filename should be Firebutton). Second, I would suggest that you set your prefab object in the inspector like this:

public Transform prefab1;

And then make your Instantiate line (also including position and rotation parameters):

GameObject dd = (GameObject)Instantiate(prefab1, transform.position, Quaternion.identity);

That may not fix your problem though. It may add to your problems :smiley:

Hope that helps, Klep

No worries! Glad I could help. :)

@kleptomaniac is right

You are trying to instantiate a prefab through a reference variable named prefab1, but the variable itself is never declared.

So, like @kleptomaniac wrote, add this line:

public GameObject prefab1;

Then in Unity Editor, drag drop your prefab to this reference so that the variable now has a correct value.

Haha, yay! I just learnt the C# way to do it then, so I'm happy. :D