# Instantiate prefab as a type that inherits from MonoBehaviour

I have a CeilingTile class. In this class, I have an InstantiateCeilingLamp() method, which instantiates from a CeilingLamp prefab.

Here is the code:

protected void InstantiateCeilingLamp()
{

CeilingLamp ceilingLamp =
Instantiate(ceilingLampPrefab, this.transform.position, Quaternion.identity)
as CeilingLamp;

if (ceilingLamp == null)
{
Debug.Log("Failed to instantiate the ceiling lamp.");
return;
}

ceilingLamp.transform.SetParent(this.transform);
}


prefabPath is a const string defined within the class.

Stepping through my code using the debugger, I can see that ceilingLampPrefab is non-null after executing AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject));.

However, Instantiate(...) as CeilingLamp; returns null, because the instantiated prefab cannot be cast to the type CeilingLamp, which inherits from MonoBehaviour.

How should I modify my code in order to instantiate a prefab as a type that inherits from MonoBehaviour?

The CeilingLamp prefab has the CeilingLamp.cs script (which inherits from MonoBehaviour) attached to it, so by modifying the code as follows, I am able to do what I want:

protected void InstantiateCeilingLamp()
{

GameObject lampObject =
Instantiate(ceilingLampPrefab, this.transform.position, Quaternion.identity)
as GameObject;

CeilingLamp ceilingLamp = lampObject.GetComponent<CeilingLamp>();

if (CeilingLamp == null)
{
Debug.Log("Failed to instantiate the ceiling lamp.");
return;
}

ceilingLamp.transform.SetParent(this.transform);
}

• I think you can simplify this substantially by making it var ceilingLampPrefab = (CeilingLamp)AssetDatabase.LoadAssetAtPath(prefabPath, typeof(CeilingLamp) then your Instantiate method will return the reference to the instance's ceiling lamp script directly. – DMGregory Dec 1 '18 at 13:06