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?
Yword
2
You can use the GameObject constructor to create a new GameObject.
Helical
3
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.
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_.getObject(), enemies*.getLocation(), transform.rotation);*_
}
}
}