- Home /
Problem was fixed by myself.
How to get object to have two or more same classes at script
Hi all,im totally new to classes and all that stuff so i want to make object to have more of same classes from one script based on one variable called enemyes:
class classtut extends MonoBehaviour {
var Enemyes : int; //this will declare how many classes we will have
class Enemy {
public var Health : float = 100;
public var Obj : GameObject;
public function En (hel : float){
hel = Health;
}
}
public var Enm : Enemy = new Enemy();
function Start () {
}
function Update () {
//number of enemyes = Enemyes
Debug.Log(Enm.Health); //for the test
//and other stuff...
}
} //sorry for my bad english :(
Answer by Tehnique · Jul 13, 2014 at 03:51 PM
List<Enemy> AllEnemies = new List<Enemy>();
Then you just use:
for(int i = 0; i < Enemyes; i++)
{
AllEnemies.Add(new Enemy());
}
My code is C#, you'll have to turn it to Js, but you get the ideea.
and how should that look like in my script,was that a C# code?
Yes, it's C#. Not a fan of Js, but I know it does not have a List, you have to use Array.
Probably something like:
var AllEnemies = new Array ();
for(var i : int = 0; i < Enemyes; i++)
{
AllEnemies.Add(new Enemy());
}
As for your script:
public var Enemyes : int = 6; //default value
public var AllEnemies = new Array ();
function Start ()
{
// Add 6 enemies.
for(var i : int = 0; i < Enemyes; i++)
{
AllEnemies.Add(new Enemy());
}
}
function Update ()
{
//print health for all enemies.
for(var i : int = 0; i < AllEnemies.Length; i++)
{
Debug.Log(AllEnemies[i].Health);
}
}
turned everything into C#,now getting: Assets/Classtutc.cs(17,9): error CS0246: The type or namespace name List
1' could not be found. Are you missing a using directive or an assembly reference?
You probably wrote something wrong. List declaration in C# is
List<Enemy> AllEnemies = new List<Enemy>();
You probably named a list "List1" but you put that name where it was expecting the type (List).
Look at line 17, character 9 in your code, as the error says.