- Home /
Is there a way to create new GameObjects in your scene from constructors?
Im trying to teach object oriented programming to a class using unity, however, they find it pretty boring since were using debug.log statements to make "hypothetical gameobjects". Is there any way to instantiate new GameObjects in unity with constructors?
Answer by Vice_Versa · Sep 23, 2015 at 05:36 AM
i figured it out its quite possible, and more efficient in my opinion. Im going to always start coding like this.
using UnityEngine; using System.Collections;
public class Enemy : MonoBehaviour {
/**
* Instance Variables
*
* */
private int health = 10;
private Vector3 myLocation;
private GameObject myObject;
public Enemy()
{
}
public Enemy(Vector3 location)
{
setLocation(location);
setObject(Resources.Load("mySphere") as GameObject);
health = 10;
}
// Use this for initialization
public GameObject getObject()
{
return myObject;
}
public Vector3 getLocation()
{
return myLocation;
}
void setObject(GameObject inputObject)
{
myObject = inputObject;
}
void setLocation(Vector3 inputV)
{
myLocation = inputV;
}
}
//
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class main : MonoBehaviour {
Enemy enemy1, enemy2, enemy3, enemy4, enemy5;
Enemy[] enemies;
ArrayList enemiesList;
// Use this for initialization
void Start () {
enemy1 = new Enemy(new Vector3(1,1,1));
enemy2 = new Enemy(new Vector3(2, 1, 1));
enemy3 = new Enemy(new Vector3(3, 1, 1));
enemy4 = new Enemy(new Vector3(4, 1, 1));
enemy5 = new Enemy(new Vector3(5, 1, 1));
enemies = new Enemy[5]{enemy1, enemy2, enemy3, enemy4, enemy5};
for(int i = 0; i < enemies.Length; i++)
{
Instantiate(enemies[i].getObject(), enemies[i].getLocation(), transform.rotation);
}
}
}
Answer by Yword · Sep 23, 2015 at 03:42 AM
You can use the GameObject constructor to create a new GameObject.
Answer by Helical · Sep 23, 2015 at 05:08 AM
Unity is not very OOP friendly. Many of my workers which were OOP Thinkers had trouble thinking Unity wise.
You could teach that there are alternatives to OOP like Unity where instead of inhereting from a MonoBehavoiur class like Quest to add a field or a function. You could just make another component and attach it to the same GameObject and have it manage itself through the Start(). Thus having a different type of Quest Object even though no inheritance was used.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Control an gameobject in a specific area 0 Answers
using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers
how to show coordinates on the prefab? Using multidimensional arrays? 0 Answers
An OS design issue: File types associated with their appropriate programs 1 Answer