- Home /
creating Custom class
Hello, i want to create my own class of cell, for example. So i have a prefab "Cell". In MainScript, that is attached to Empty game object i want to create array of this class. So cell class:
public class Cell : MonoBehaviour { GameObject CellSprite; public Cell() { Instantiate(CellSprite, new Vector3(0, 0, 0), Quaternion.identity); } }
But the problem is, that i cant use "new" keyword in MainScript to create Cells, because of deriving from monobehaviour. if i not derive from monobehaviour, i cant call Instantiate() in Cell;
So i want to create custom Class "Cell", that would be encapsulating all logic for it. i understand, that i can create array of GameObject`s in MainScript and call instantiate there, but i dont want. So what is the solution for this? Thanks)
Answer by tw1st3d · Jul 26, 2013 at 03:17 PM
CellDev.cs
using UnityEngine;
using System.Collections;
using System;
public namespace CellDev
{
public class Cell : Component
{
public GameObject cellSprite;
public Vector3 pos = new Vector3(0, 0, 0);
void Start()
{
CreateCell(cellSprite);
}
public void CreateCell(GameObject sprite)
{
Instantiate(sprite, pos, Quaternion.identity);
}
}
}
UsingCell.cs
using UnityEngine;
using System.Collections;
using System;
using CellDev; //Importing your namespace here
public class UsingCell
{
public Cell cL = new Cell();
void Start()
{
}
void Update()
{
}
}
But this way i cant see GameObject in the inspector of Cell script
Define it with a tag in the code. If you want to actually create a full game you're going to need to know how to do things without the inspector.
Ok, i get it. It is not the question of this topic, but: i tried to FindGameObjectwithTag, if this object is pefab, it isnt finded, and if it is in the scene, everything works. So what is the difference to find prefab or its clone on the scene?
Your answer
![](https://koobas.hobune.stream/wayback/20220613110926im_/https://answers.unity.com/themes/thub/images/avi.jpg)