- Home /
Instantiating gameObject with custom Class properties
Hi guys! I`m just starting to learn about classes and although I can grasp the basic concepts of what a class is, some things are making my head ache. So basically I have made class that holds some properties. I now want to spawn a cube, that is of this class, so that I would have a cube, that already has the properties defined by me.
Heres that last version of code I tried:
public static int arrLen=8;
public static int arrWid=8;
public GameObject cube;
public Cell[,] cellsArr = new Cell[arrLen,arrWid];
private Cell cell;
public class Cell
{
public float x;
public float y;
public int state;
public GameObject prefab;
public GameObject cellRef;
public Transform parentTransform;
public Cell(float x, float y,GameObject cellFab)
{
this.x =x;
this.y = y;
this.prefab = cellFab;
}
}
void Awake()
{
//instantiate the whole array of cubes
for (int i = 0; i<arrLen; i++)
{
for(int j = 0; j<arrWid; j++)
{
cell = Instantiate (cube, new Vector3(i,j,0),Quaternion.identity) as Cell;
cellsArr[i,j] = cell;
}
}
}
Now I get this error: Assets/Scripts/Algorithm.cs(47,91): error CS0039: Cannot convert type UnityEngine.Object' to
Algorithm.Cell' via a built-in conversion
What am I doing wrong and what would be a possible solution?
Answer by Jamora · Jun 15, 2013 at 03:22 PM
You cannot instantiate your own classes (unless they're ScriptableObjects). Instead, you either instantiate a GameObject and add your own class as component, or instantiate a prefab, that already has yor custom class added to it.
I assume your cube
is a prefab that has your script added, so try the following:
GameObject temp = Instantiate (cube, new Vector3(i,j,0),Quaternion.identity) as GameObject;
cellsArr[i,j] = temp.GetComponent<this>().cell;
For my snippet to work, you'll need to make your cell
variable public and have your cell
initialized.
Thanks mate! :) I understand that this code gets the class properties from the script attached to the object. How would I then make an object have a class properties that are defined in script I am instantiating the object from?
You would replace temp.GetComponent<this>() by whatever type you want to get from the GameObject (that also has a public Cell cell
... If I understood you correctly.
Your answer
Follow this Question
Related Questions
how to instantiate object when I click 1 Answer
object not spawning but no error message 2 Answers
Calling an object from a different JS Script and Instantiate it 1 Answer
Alternative to using prefabs w/scripts to save sets of data for use at runtime? 1 Answer
C# cast object to gameobject not working 2 Answers