The name 'Instantiate' does not exist in the current context

6.9k views Asked by At

I'm learning Unity C#, I was doing a tutorial from Unity, 2d roguelike, we are trying to instantiate the floor tiles, I did exactly the same as in the video (actually I even copied the code) but it shows me an error on the line

GameObject instance = Instantiate(toInstantiate, new Vector3(x, y, 0f), 
    Quaternion.identity) as GameObject; 

specifically with Instantiate(toInstantiate).

Can you help me?

using UnityEngine;
using System;
using System.Collections.Generic;
using Random = UnityEngine.Random;

public class BoardManager : MonoBehaviour 
{
    // Other class code omitted

    void BoardSetup()
    {
        boardHolder = new GameObject("Board").transform;

        for (int x = -1; x < columns + 1; x++)
        {
            for (int y = -1; y < rows + 1; y++)
            {
                GameObject toInstantiate = floorTiles[Random.Range(0, floorTiles.Length)];

                if (x == -1 || x == columns || y == -1 || y == rows)
                    toInstantiate = outerWallTiles[Random.Range(0, outerWallTiles.Length)];

                GameObject instance = Instantiate(toInstantiate, new Vector3(x, y, 0f), 
                    Quaternion.identity) as GameObject;

                instance.transform.SetParent(boardHolder);
            }
        }
    }
}
3

There are 3 answers

2
David On BEST ANSWER

Instantiate is (usually) a reference to Object.Instantiate, so the class in which you're coding needs to derives from unity's Object class; this is most commonly done by inheriting from MonoBehaviour which in turn inherits from Object. Keep in mind that any method you reference by name alone needs to exist within the same class or inheritance.

1
MajidJafari On

You can also call it like UnityEngine.Object.Instantiate in the Non-MonoBehaviour C# class. You must include using UnityEngine; at the top of the class definition, though.

3
KYL3R On

See if you have the includes ("using directive") correct, and additionally, as @Haytam said, check if your class looks like this (note MonoBehaviour):

using UnityEngine;
using System.Collections;

public class YourTutorialClass : MonoBehaviour {

You can try an example from the docs about Instantiate to find your problem.