0
\$\begingroup\$

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()
{
    Object ceilingLampPrefab = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject));

    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?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

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()
{
    Object ceilingLampPrefab = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject));

    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);
}
\$\endgroup\$
1
  • 1
    \$\begingroup\$ 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. \$\endgroup\$
    – DMGregory
    Commented Dec 1, 2018 at 13:06

You must log in to answer this question.