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\$
0
\$\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);
}
| improve this answer | |
\$\endgroup\$
  • \$\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 Dec 1 '18 at 13:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy