Using Instantiate for the first time and, although it works I was wondering if there was a way to Instantiate a prefab as a Monobehaviour Class instead of as a GameObject
This is my complete code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DeployBoard : MonoBehaviour {
public List<GameObject> Tiles { get; set; }
public GameObject tilePrefab;
public GameObject tileHolder;
public int initX = -9;
public int initZ = 9;
void Start () {
GameObject tileInstance;
Tiles = new List<GameObject>();
Debug.Log("0 ASSERT DeployBoard Start ");
for (int i = 1; i <= 8; i++)
{
for (int j = 1; j <= 8; j++)
{
int xVal;
int zVal;
tileInstance = Instantiate(tilePrefab,new Vector3(xVal, 0, zVal), Quaternion.Euler(0, 0, 0)) as GameObject;
Tiles.Add(tileInstance);
tileInstance.transform.SetParent(tileHolder.transform, false);
}
}
}
}
Yup! Don’t make tilePrefab a GameObject. Make it whatever MonoBehaviour you’re trying to instantiate. You can still drag-drop a prefab onto the Inspector slot. It will find the component you’re looking for.
Note that your Instantiate call is outdated. Since 5.5 (5.6?), it’s no longer necessary to cast tileInstance to GameObject, Instantiate returns the same type as whatever you’re instantiating.
Wow; sorry for necroing the thread but I just ran into this and wanted to highlight how weird (and potentially useful) that is. To summarize and make sure I get this right (someone correct me if this is wrong):
Dragging a prefab GameObject into a Monobehavior property automagically pulls ONLY the corresponding Monobehavior component of the GameObject into the property (and I’m assuming the editor ensures you cannot drag any GameObject onto such a field if the GameObject does not contain a compatible component).
That’s a cool shortcut, but not obvious, as it somewhat goes counter of the expected behavior of “this property is an object of this type and that’s what you drag here” (GameObject vs Component).
Dropping a GameObject onto a property will automatically pull the appropriate reference based on the given property type (if it has the required component). The Inspector won’t let you drop it there if it doesn’t have the required component. All components have a .gameObject and a .transform property you can access from their script which are the actual GameObject they’re attached to, not “their own” - just mentioning that for anyone the concept’s new to.
You can create a new component that has for example a public Renderer ren;, public MeshFilter mf;, then add that component to a GameObject. Then, if you also add a MeshRenderer and a MeshFilter component to the same GameObject, you can either drag that GameObject from the Scene hierarchy into both of the properties (each property then having a reference to the corresponding component), -or-, right from within the Inspector, you can drag the top bar of those 2 components one after another into the appropriate property of the new component you added.